用具有特殊字符的字符串替换 shell 脚本中的字符串

Replace a string in shell script by a string with special character

我正在尝试用具有特殊字符的字符串替换 shell 脚本中的字符串:

name="test&commit"
echo "{{name}}" | sed "s/{{name}}/$name/g"

我得到的结果是

test{{name}}commit

我知道在 & 之前添加 \ 会使其工作,但名称参数是由用户给出的,所以我希望我的代码能够预测到这一点。有人知道如何实现吗?

您需要使用另一个 sed 命令在给定输入字符串中的所有特殊字符前添加一个反斜杠。

$ name="test&commit"
$ name1=$(sed 's/[^[:alpha:][:digit:][:blank:]]/\&/g' <<<"$name")
$ echo $name1
test\&commit
$ echo "{{name}}" | sed "s/{{name}}/$name1/g"
test&commit

它将被最小化为,

$ name="test&commit"
$ echo "{{name}}" | sed "s/{{name}}/$(sed 's/[^[:alpha:][:digit:][:blank:]]/\&/g' <<<"$name")/g"
test&commit

在 perl 中,您可以使用 \Q \P 关闭表达式。
我填写 vars 模板、占位符和名称:

$ echo "template=$template"
template=The name is {{name}} and we like that.
$ echo "placeholder=$placeholder"
placeholder={{name}}
$ echo "name=$name"
name=test&commit

替换将用

执行
$ echo $template | perl -pe 's/\Q'$placeholder'\E/'$name'/g'
The name is test&commit and we like that.

稍微改变提供模板和值的方式:

$ cat template

   Dear {{name}}
    I hope to see you {{day}}.

(模板是一个文件{{var}},要用值实例化)

$ name='Mary&Susan' day=tomorrow    perl -pe 's/{{(\w+)}}/$ENV{}/g' template

   Dear Mary&Susan,
    I hope to see you tomorrow.