I want to use sed to change a slash into a backslash and a slash, i.e. / -> \/. But it does not work. Here a small example:

echo $TEST
echo $TEST | sed "s/hallo/bello/g"
echo $TEST | sed "s/\//\\\//g"

The output of the first three lines is as assumed. But the last one does not work. Why? How to correct the last part?

  • 5
    When in doubt, echo the command: echo sed "s/\//\\\//g" -> sed s/\//\\//g. Btw you can use something else for sed, like 's@/@\\/@g'. Jun 24, 2015 at 13:28

2 Answers 2


Use single quotes for the expression you used:

sed 's/\//\\\//g'

In double quotes, \ has a special meaning, so you have to backslash it:

sed "s/\//\\\\\//g"

But it's cleaner to change the delimiter:

sed 's=/=\\/=g'
sed "s=/=\\\/=g"
  • 14
    Alternate delimiters are awesome. May 30, 2017 at 14:22
  • Seem like end-of-line ($) and beginning-of-line (^) are handled differently, if at all, when using single quotes. What's going on with them?
    – not2qubit
    Jul 23, 2019 at 21:17
  • @not2qubit: Can you provide an example? $ might be special in double quotes, but should be OK in single quotes.
    – choroba
    Jul 23, 2019 at 21:22
  • I tried to remove \ from the end of lines with: cat file.h | sed -zE 's/\\$//g' and that didn't work. However, without the $ it worked, but then it also catches stuff in between.
    – not2qubit
    Jul 23, 2019 at 21:33
  • 2
    @not2qubit: Under -z, $ matches at a null byte, not at a newline.
    – choroba
    Jul 23, 2019 at 21:50


sed 's/\//\\\//g'

or using another delimiter to prevent you from escaping slash:

sed 's,/,\\/,g'

Not the answer you're looking for? Browse other questions tagged or ask your own question.