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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With