Linux 用双引号括起来的双反斜杠替换正斜杠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17379293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:21:12  来源:igfitidea点击:

Replace forward slash with double backslash enclosed in double quotes

linuxbashsed

提问by wa4557

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

不起作用,我不知道为什么。它总是只替换一个反斜杠而不是两个

采纳答案by piokuc

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:

When/是正则表达式的一部分,您想用 的s(替代)命令替换它sed,您可以在命令的语法中使用其他字符而不是斜杠,因此您可以这样写,例如:

sed 's,/,\\,g'

above ,was used instead of the usual slash to delimit two parameters of the scommand: 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

回答by gniourf_gniourf

How about this?

这个怎么样?

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

Demo in a shell:

在 shell 中演示:

$ var=a/b/c
$ a=${var//\//\\}
$ echo "$a"
a\b\c

回答by jaypal singh

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

另一种方法: tr '/' '\'

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