Whether to escape ( and ) in regex using GNU sed Whether to escape ( and ) in regex using GNU sed bash bash

Whether to escape ( and ) in regex using GNU sed


This part of the gnu sed manual you linked to explains that whether you should escape parentheses depends on whether you are using basic regular expressions or extended regular expressions. This part says that the -r flag determines what mode you are in.

Edit: as stated in grok12's comment, the -E flag in bsd sed does what the -r flag does in gnu sed.


Originally sed, like grep and everything else, used \( to indicate grouping, whereas ( just matched a literal open-paren.

Many newer implementations of regular expressions, including egrep and perl, switched this around, so \( meant a literal open-paren, and ( was used to specify grouping.

So now with gnu sed, ( is a special character; just like egrep. But on other systems (e.g. BSD) it's still the old way, as far as I can tell. Unfortunately this is a real mess, because now it's hard to know which one to use.


Thanks to rocker, murga, and chris. Each of you helped me understand the issue. I'm answering my own question here in order to (hopefully) put the whole story together in one place.

There are two major versions of sed in use: gnu and bsd. Both of them require parens in basic regex to be escaped when used for grouping but not escaped when used in extended regex. They diff in that the -r option enables extended regex for gnu but -E does so for bsd.

The standard sed in mac OSX is bsd. I believe much of the rest of the world uses gnu sed as the standard but I don't know precisely who uses what. If you are unsure which you are using try:

> sed -r

If you get a

> sed: illegal option -- r

reply then you have bsd.