Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace forward slash with double backslash enclosed in double quotes

Tags:

linux

bash

sed

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

like image 630
wa4557 Avatar asked Jun 29 '13 10:06

wa4557


People also ask

How do you make a double slash in Python?

This is because \2 has a special meaning in a python string. If you wish to specify \ then you need to put two \\ in your string. This is a "raw" string, and very useful in situations where you need to use lots of backslashes such as with regular expression strings.

How do you replace a backslash?

To replace all backslashes in a string:Call the replaceAll() method, passing it a string containing two backslashes as the first parameter and the replacement string as the second. The replaceAll method will return a new string with all backslashes replaced by the provided replacement.

What is a double backslash?

Two backslashes are used as a prefix to a server name (hostname). For example, \\a5\c\expenses is the path to the EXPENSES folder on the C: drive on server A5. See UNC, \\, path and forward slash.


1 Answers

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
like image 71
piokuc Avatar answered Sep 22 '22 15:09

piokuc