46

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:

#!/bin/bash
TEST=/etc/hallo
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?

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

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"
| improve this answer | |
  • 10
    Alternate delimiters are awesome. – kevlarjacket May 30 '17 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 '19 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 '19 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 '19 at 21:33
  • 1
    @not2qubit: Under -z, $ matches at a null byte, not at a newline. – choroba Jul 23 '19 at 21:50
18

Try:

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

or using another delimiter to prevent you from escaping slash:

sed 's,/,\\/,g'
| improve this answer | |

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