sed replace using string containing backslashes

2019-09-15 19:29发布

问题:

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