53

I have to replace ( with some character in my file, and I can't do it. \( is used for grouping in sed and when I used \\( with sed, it treated it as \( character not as just (. It seems like a tricky case to me.

N.N.
  • 1,980
dwwdw
  • 965
  • 10
    Suggestion: if you just want to substitute a character for another, use tr(anslate): echo 'Hello (world)' | tr '()' '[]'; it outputs Hello [world]. – Lekensteyn Feb 08 '13 at 18:42

1 Answers1

77

If you use sed without -r (extended regular expressions) it will work as it uses \(\) rather than () for grouping:

sed -e 's/(/X/g'

For example

$ echo "foo (bar) (baz)" | sed -e 's/(/X/g'
foo Xbar) Xbaz)

If you want to use -r you can put ( inside [], e.g.

sed -re 's/[(]/X/g'

As Lekensteyn remarks using tr might be more appropriate as you are merely replacing and you do not need the full power of regular expressions.

N.N.
  • 1,980
  • 7
    TL;DR: Don't escape it. – qwertzguy May 05 '15 at 23:46
  • I used this to replace php's deprecated "split" with "explode" function, making sure "split" is preceded by a space and followed by a "(". grep -lRZ " split(" . | xargs -0 sed -i -e 's/ split(/ explode(/g' – Buttle Butkus Jun 04 '16 at 02:01