Bash Sed – Escaping Forward and Back Slashes

bashsed

I have the following string: /tmp/test/folder1/test.txt

I wish to use sed to substitute / for \/ – for example:

\/tmp\/test\/folder1\/test.txt

So I issue:

echo "/tmp/test/folder1/test.txt" | sed "s/\//\\\\//g"

Although it returns:

sed: -e expression #1, char 9: unknown option to `s'

I am escaping the forward slash and backslash – so not sure where I have gone wrong here

Best Answer

You need to escape (with backslash \) all substituted slashes / and all backslashes \ separately, so:

$ echo "/tmp/test/folder1/test.txt" | sed 's/\//\\\//g'
\/tmp\/test\/folder1\/test.txt

but that's rather unreadable.

However, sed allows to use almost any character as a separator instead of /, this is especially useful when one wants to substitute slash / itself, as in your case, so using for example semicolon ; as separator the command would become simpler:

echo "/tmp/test/folder1/test.txt" | sed 's;/;\\/;g'

Other cases:

  • If one wants to stick with slash as a separator and use double quotes then all escaped backslashes have to be escaped one more time to preserve their literal values:

    echo "/tmp/test/folder1/test.txt" | sed "s/\//\\\\\//g"
    
  • if one doesn't want quotes at all then yet another backslash is needed:

    echo "/tmp/test/folder1/test.txt" | sed s/\\//\\\\\\//g
    
Related Question