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

后端 未结 2 472
我在风中等你
我在风中等你 2021-01-27 01:22

Please see these simple commands:

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

The \\U is eaten. Other backslashes

相关标签:
2条回答
  • 2021-01-27 01:49

    You could reparse $tmp itself through sed

    echo "a" | sed "s|a|$(echo ${tmp} | sed 's|\\|\\\\|g')|g"
    
    0 讨论(0)
  • 2021-01-27 01:51

    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[_
    
    0 讨论(0)
提交回复
热议问题