一个字符串替换shell脚本中的字符串特殊字符
问题描述:
我试图用特殊字符的字符串替换shell脚本中的字符串:一个字符串替换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表达式。
我填的是瓦尔模板,占位符和名称:
$ 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{$1}/g' template
Dear Mary&Susan,
I hope to see you tomorrow.
这个'name1 = $(sed's/[[:punct:]]/\\&g' NeronLeVelu
'cntrl'类是添加到'punct',而不是替换:-) – NeronLeVelu
所有你真正需要的是'sed's/[&/ \]/\\&g''。请参阅http://stackoverflow.com/a/29626460/1745001。 –