80

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?

wjandrea
  • 658
devopsfun
  • 1,407
  • 6
    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

2 Answers2

158

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"
choroba
  • 47,233
  • 22
    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
  • 2
    @not2qubit: Under -z, $ matches at a null byte, not at a newline. – choroba Jul 23 '19 at 21:50
  • I was sure to have tried it also without. Can it have something to do with the file character encoding or EOL settings? (I.e. UTF-8 vs ASCII, and \r vs \r\n?) – not2qubit Jul 24 '19 at 07:50
  • Yes, $ doesn't match before \r. – choroba Jul 24 '19 at 09:24
  • More about alternate delimiters: https://backreference.org/2010/02/20/using-different-delimiters-in-sed/index.html You can use almost anything char as a delimiter, even spaces! – akwky Sep 26 '22 at 09:34
27

Try:

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

or using another delimiter to prevent you from escaping slash:

sed 's,/,\\/,g'
cuonglm
  • 153,898