How can I insert a variable containing a backslash

2020-04-26 01:37发布

问题:

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"