[英]Replace forward slash with double backslash enclosed in double quotes
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
它总是只用一个反斜杠替换而不是两个
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
(替换)命令替换的正则表达式的一部分时,可以在命令的语法中使用其他字符而不是斜杠,因此您可以编写,例如:
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. 上面
,
使用而不是通常的斜杠来分隔s
命令的两个参数:描述要替换的部分的正则表达式和用作替换的字符串。
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.
反斜杠是一个特殊的(引用)字符,因此必须引用它,这里引用它,这就是为什么我们需要4个反斜杠来表示两个反斜杠。
$ echo /etc/passwd| sed 's,/,\\\\,g'
\\etc\\passwd
How about this? 这个怎么样?
a=${var//\//\\\\}
Demo in a shell: 在shell中演示:
$ var=a/b/c
$ a=${var//\//\\\\}
$ echo "$a"
a\\b\\c
Another way of doing it: tr '/' '\\'
另一种方法:
tr '/' '\\'
$ var=a/b/c
$ echo "$var"
a/b/c
$ tr '/' '\' <<< "$var"
a\b\c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.