How to translate sed "s" command from double to single quotes

Viewed 77

My problem is that I have this command:

sed -i -E 's/((^|\s)PATH=)([^\$]*)$/\1${PATH:-\3}/g' /foo

and as far as I use it with single quotes it works fine but now I need to use it with double-quotes (because Dockerfile doesn't like single ones) and when I try to translate it to:

"s/((^|\s)PATH=)([^\$]*)$/\1${PATH:-\3}/g"

I get this error: unknown option to `s'. So I read that I can try to replace the separators and I tried with @:

"s@((^|\s)PATH=)([^\$]*)$@\1${PATH:-\3}@g"

But with that I get: unterminated `s' command. I also tried to replace with ;:

"s;((^|\s)PATH=)([^\$]*)$;\1${PATH:-\3};g"

and that "succeeded" but the end result was different to what I expected. Any ideas on how can I translate this properly to use it with doubled-quotes?

2 Answers

Don't! You can easily translate it to a string with backslashes and no quotes:

$ printf "%q\n" 's/((^|\s)PATH=)([^\$]*)$/\1${PATH:-\3}/g'
s/\(\(\^\|\\s\)PATH=\)\(\[\^\\\$\]\*\)\$/\\1\$\{PATH:-\\3\}/g

$ sed -E s/\(\(\^\|\\s\)PATH=\)\(\[\^\\\$\]\*\)\$/\\1\$\{PATH:-\\3\}/g

As mentioned by @glenn jackman escaping backslashes and dollar signs does the work, this worked for me:

"s/((^|\\s)PATH=)([^\\\$]*)\$/\\1\${PATH:-\\3}/g"

Thanks!

Related