Search code examples
macossedzshslash

zsh sed distinguish "\(" from "("


I'm doing some string editing from a zsh script (on Mac OS Catalina). Some of the strings have a parentheses with a slash before and some don't (usually a space before).

I'm trying to write a command that ignores a left parenthesis unless it has a slash beforehand.

So the command...

sed 's/"\("/"\\\("/g'

...would not be triggered by...

"foo (bar)" 

...but would be triggered on...

"foo \(bar)"

Solution

  • You may use

    sed 's/\\*(/\\\\(/g' file > outfile
    

    Here, \\*( matches any amount of \ and then ( and the \\\\( replacement actually replaces with two \ chars and then (. It is necessary to use double backslash in the replacement part to represent one backslash because \ is used to encode backreferences (like \1, \2, etc.).