Replace one substring for another string in shell script

前端 未结 10 1635
猫巷女王i
猫巷女王i 2020-11-22 11:55

I have \"I love Suzi and Marry\" and I want to change \"Suzi\" to \"Sara\".

#!/bin/bash
firstString=\"I love Suzi and Marry\"
secondString=\"Sara\"
# do some         


        
10条回答
  •  甜味超标
    2020-11-22 12:08

    It's better to use bash than sed if strings have RegExp characters.

    echo ${first_string/Suzi/$second_string}
    

    It's portable to Windows and works with at least as old as Bash 3.1.

    To show you don't need to worry much about escaping let's turn this:

    /home/name/foo/bar
    

    Into this:

    ~/foo/bar
    

    But only if /home/name is in the beginning. We don't need sed!

    Given that bash gives us magic variables $PWD and $HOME, we can:

    echo "${PWD/#$HOME/\~}"
    

    EDIT: Thanks for Mark Haferkamp in the comments for the note on quoting/escaping ~.*

    Note how the variable $HOME contains slashes but this didn't break anything.

    Further reading: Advanced Bash-Scripting Guide.
    If using sed is a must, be sure to escape every character.

提交回复
热议问题