用双引号中的双反斜杠替换正斜杠

用双引号中的双反斜杠替换正斜杠

本文介绍了用双引号中的双反斜杠替换正斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我极力尝试用双引号("\\")内的双反斜杠替换正斜杠(/)

I'm desperately trying to replace a forward slash (/) with double backslash enclosed in double quotes ("\\")

但是

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

推荐答案

/是要用seds(替代)命令替换的正则表达式的一部分时,可以使用命令语法中使用其他字符而不是斜杠,因此您可以编写例如:

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'

,上方使用

而不是通常的斜杠来分隔s命令的两个参数:描述要替换部分的正则表达式和用作替换的字符串.

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.

以上将用两个反斜杠替换每个斜杠.反斜杠是一个特殊的(引号)字符,因此必须加引号,在这里用引号引起来,这就是为什么我们需要4个反斜杠来表示两个反斜杠的原因.

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

这篇关于用双引号中的双反斜杠替换正斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:09