sed使用包含反斜杠的字符串进行替换 [英] sed replace using string containing backslashes

查看:706
本文介绍了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


推荐答案

您必须转义<$ c $中的元字符c> 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

这篇关于sed使用包含反斜杠的字符串进行替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆