Replace a slash with a double backslash enclosed in double quotes

I am desperately trying to replace the slash ( / ) with a double backslash enclosed in double quotes ( "\\" )

but

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

doesn't work, and I have no idea why. It is always replaced with only one backslash, not two

+8
linux bash sed
source share
3 answers

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

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

above , used instead of the usual slash to distinguish between two parameters of the s command: a regular expression that describes the replaced part, and a string to be used as a replacement.

The above will replace each slash with two backslashes. A backslash is a special (quoted) character, so it must be quoted, here it quotes on its own that we need 4 backslashes to represent two backslashes.

 $ echo /etc/passwd| sed 's,/,\\\\,g' \\etc\\passwd 
+21
source share

How about this?

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

Demo in the shell:

 $ var=a/b/c $ a=${var//\//\\\\} $ echo "$a" a\\b\\c 
+14
source share

Another way to do this: tr '/' '\'

 $ var=a/b/c $ echo "$var" a/b/c $ tr '/' '\' <<< "$var" a\b\c 
0
source share

All Articles