sed使用包含反斜杠的字符串进行替换
我需要使用包含反斜杠(REVERSE SOLIDUS)字符的Windows样式目录路径替换文件中的文本。我已经在使用替代表达式分隔符。反斜杠似乎被视为转义字符。
I need to replace text in a file with a Windows-style directory path containing backslash (REVERSE SOLIDUS) characters. I am already using an alternative expression delimiter. The backslashes appear to be treated as escape characters.
如何在输出中保留反斜杠?
How can I keep the backslashes in the output?
$ echo DIR=foobar | sed -e "s#DIR=.*#$(cygpath -w $(pwd))#"
C:gwin64homelit
所需的输出是:
C:\cygwin64\home\lit
您必须转义 sed 替换模式。幸运的是,其中只有三个:&
, \
和定界符 /
(请参阅此问题和此)。在您的情况下,由于您使用#
作为分隔符,因此必须转义#
而不是 /
。
You'll have to escape metacharacters in sed
replacement pattern. Fortunately, there are only three of those: &
, \
, and a delimiter /
(see this question and this). In your case, since you're using #
for delimiter, you'll have to escape #
instead of /
.
您可以创建一个帮助程序shell函数(例如此处):
You can create a helper shell function (like here):
escapeSubst() { sed 's/[&#\]/\\&/g'; }
,然后将字符串传递给 sed
,像这样:
and then pass your string through it before giving it to sed
, like this:
$ echo DIR=foobar | sed -e "s#DIR=.*#$(cygpath -w $(pwd) | escapeSubst)#"
C:\cygwin64\home\lit