How can I insert a variable containing a backslash in sed?

不打扰是莪最后的温柔 提交于 2020-03-16 08:01:50

问题


Please see these simple commands:

$ echo $tmp
UY\U[_
$ echo "a" | sed "s|a|${tmp}|g"
UY[_

The \U is eaten. Other backslashes won't survive either.

How can I make the above command work as expected?


回答1:


If it's only backslash that is "eaten" by sed and escaping just that is enough, then try:

echo "a" | sed "s|a|${tmp//\\/\\\\}|g"

Confusing enough for you? \\ represents a single \ since it needs to be escaped in the shell too. The inital // is similar to the g modifier in s/foo/bar/g, if you only want the first occurring pattern to be replaced, skip it.

The docs about ${parameter/pattern/string} is available here: http://www.gnu.org/s/bash/manual/bash.html#Shell-Parameter-Expansion

Edit: Depending on what you want to do, you might be better of not using sed for this actually.

$ tmp="UY\U[_"
$ in="a"
$ echo ${in//a/$tmp}
UY\U[_



回答2:


You could reparse $tmp itself through sed

echo "a" | sed "s|a|$(echo ${tmp} | sed 's|\\|\\\\|g')|g"


来源:https://stackoverflow.com/questions/7512309/how-can-i-insert-a-variable-containing-a-backslash-in-sed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!