0

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
lit
  • 14,456
  • 10
  • 65
  • 119
  • this might help https://stackoverflow.com/questions/29613304/is-it-possible-to-escape-regex-metacharacters-reliably-with-sed ... or if you have `perl`, save the result in variable, for ex: `a=$(cygpath -w $(pwd))` and try `perl -pe "s#DIR=.*#q($a)#e"` or if `PWD` env variable works: `perl -pe "s#DIR=.*#q($PWD)#e"` – Sundeep Aug 21 '17 at 16:00

1 Answers1

0

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
randomir
  • 17,989
  • 1
  • 40
  • 55