sed replace using string containing backslashes

旧城冷巷雨未停 提交于 2020-01-07 04:03:09

问题


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

The desired output is:

C:\cygwin64\home\lit

回答1:


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 /.

You can create a helper shell function (like here):

escapeSubst() { sed 's/[&#\]/\\&/g'; }

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


来源:https://stackoverflow.com/questions/45801250/sed-replace-using-string-containing-backslashes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!