I have the following string: /tmp/test/folder1/test.txtI wish to use sed to substitute / for \/ - for example:\/tmp\/test\/folder1\/test.txtSo I issue:echo /tmp/test/folder1/test.txt | sed s/\//\\\\//gAlthough 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
Escaping both forward slash and back slash with sed
bash;sed
You need to escape (with \) all substituted / and all backslashes \ separately, so:$ echo /tmp/test/folder1/test.txt | sed 's/\//\\\//g'\/tmp\/test\/folder1\/test.txtbut 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 e.g.;:$ echo /tmp/test/folder1/test.txt | sed 's;/;\\/;g'\/tmp\/test\/folder1\/test.txtIf one wants to use double quotes then all escaped backslashes have to be escaped one more time to preserves its literal value:echo /tmp/test/folder1/test.txt | sed s/\//\\\\\//gand if one doesn't want quotes at all, one needs yet another backslash:echo /tmp/test/folder1/test.txt | sed s/\\//\\\\\\//g