How to replace placeholder character or word in variable with value from another variable in Bash?

后端 未结 8 1957
死守一世寂寞
死守一世寂寞 2020-12-08 14:01

I\'m trying to write a simple Bash script. I have a simple \"template\" variable:

template = \"my*appserver\"

I then have a function (

8条回答
  •  时光说笑
    2020-12-08 14:13

    I needed to do something like this, but I needed sed and the replace clause needed to include a variable. I ended up with this.

    Where the variable name is $puttyline

    sed "s/\(\[remote .origin.\]\)/\1\n$puttyline/"
    

    So sed searches for [remote "origin"] and remembers the match, and inserts a line right after, containing whatever's in the variable $puttyline.

    This can get ugly however if $puttyline contains any special characters that sed would react to, like \ or $. You have to either escape them prior with another call to sed, or... do something smarter in bash that I'm too crappy with bash to know. For example, to double-escape all backslashes:

    sed 's/\\/\\\\/g'
    

提交回复
热议问题