Reputation: 1425
I am currently running the following command and getting a "bad option in substitution" error. What I would like to do is add a backslash to the string I am replacing but I am unable to do so. Any ideas?
Code:
VAR="/host/test"
echo ${VAR} | sed -e "s/\//\\\//g"
Upvotes: 0
Views: 2610
Reputation: 85767
Why use sed at all?
$ echo "${VAR//\//\\/}"
\/host\/test
It looks a bit horrible, but it works fine. See ${parameter/pattern/string}
in https://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion.
Your problem happens because you're using double quotes ("
) around your sed code, not single quotes ('
).
In double quotes, \\
is interpreted as the escape sequence for a single \
, so the code that sed ends up seeing is:
$ echo "s/\//\\\//g"
s/\//\\//g
#^ ^ ^
sed reads this as "search for \/
and replace it by \\
, with /g
as options". This is an error because /
is not a valid option.
Upvotes: 3