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: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: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:
if one doesn't want quotes at all then yet another backslash is needed: