26

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.

  • 7
    Suggestion: if you just want to substitute a character for another, use tr(anslate): echo 'Hello (world)' | tr '()' '[]'; it outputs Hello [world]. – Lekensteyn Feb 8 '13 at 18:42
43

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.

  • TL;DR: Don't escape it. – qwertzguy May 5 '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 4 '16 at 2:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.