Unix & Linux: Escaping both forward slash and back slash with sed (3 Solutions!!)
Channel: Roel Van de Paar
Date: 2020-08-17

Unix & Linux: Escaping both forward slash and back slash with sed


The Question: 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

Solutions: Please watch the whole video to see all solutions, in order of how many people found them helpful

== This solution helped 27 people ==
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

== This solution helped 6 people ==
Or, if the value is in a (bash) shell variable:
var=/tmp/test/folder1/test.txt
$ echo "${var////\/}"
/tmp/test/folder1/test.txt
The first // start https://www.gnu.org/software/bash/manual/bashref.html#Shell-
Parameter-Expansion, saying to replace all matches with the replacement. The
next / is the escaped / to match, and the \/ is an escaped followed by an
escaped / as the replacement.

With thanks & praise to God, and with thanks to the many people who have made this project possible! | Content (except music & images) licensed under cc by-sa 3.0 | Music: https://www.bensound.com/royalty-free-music | Images: https://stocksnap.io/license & others | With thanks to user jimmij (https://unix.stackexchange.com/users/80886), user Jeff Schaller (https://unix.stackexchange.com/users/117549), user James (https://unix.stackexchange.com/users/241485), user Isaac (https://unix.stackexchange.com/users/232326), and the Stack Exchange Network (http://unix.stackexchange.com/questions/379572). Trademarks are property of their respective owners. Disclaimer: All information is provided "AS IS" without warranty of any kind. You are responsible for your own actions. Please contact me if anything is amiss at Roel D.OT VandePaar A.T gmail.com.