10

I'm desperately trying to replace a forward slash (/) with double backslash enclosed in double quotes ("\\")

but

a=`echo "$var" | sed 's/^\///' | sed 's/\//\"\\\\\"/g'`

does not work, and I have no idea why. It always replaces with just one backslash and not two

doubleDown
  • 8,048
  • 1
  • 32
  • 48
wa4557
  • 953
  • 3
  • 13
  • 25

3 Answers3

27

When / is part of a regular expression that you want to replace with the s (substitute) command of sed, you can use an other character instead of slash in the command's syntax, so you write, for example:

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

above , was used instead of the usual slash to delimit two parameters of the s command: the regular expression describing part to be replaced and the string to be used as the replacement.

The above will replace every slash with two backslashes. A backslash is a special (quoting) character, so it must be quoted, here it's quoted with itself, that's why we need 4 backslashes to represent two backslashes.

$ echo /etc/passwd| sed 's,/,\\\\,g'
\\etc\\passwd
piokuc
  • 25,594
  • 11
  • 72
  • 102
21

How about this?

a=${var//\//\\\\}

Demo in a shell:

$ var=a/b/c
$ a=${var//\//\\\\}
$ echo "$a"
a\\b\\c
gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
  • 1
    Nice. I didn't realize until I saw that this adding a second forward slash at the start of the replacement makes makes it global. Very useful! – Keith Hughitt Sep 10 '16 at 17:21
  • busybox ash(BusyBox v1.21.1,v1.22.1) has a trouble with '/' substitution $ a=abc/abc/abc $ echo ${a//c/_} ab_/ab_/ab_ $ echo ${a//\//_} abc/abc/abc – yurenchen Mar 23 '17 at 03:28
0

Another way of doing it: tr '/' '\'

$ var=a/b/c
$ echo "$var"
a/b/c
$ tr '/' '\' <<< "$var"
a\b\c
jaypal singh
  • 74,723
  • 23
  • 102
  • 147