1

Are Unix's tool regex fully compatible ?

For instance, if I grep -oE "\$text *\( *([^)]) *\)", am I garanteed to replace the exact portion I got if I use sed -E "s/\$text *\( *([^)]) *\)/replacement/g" ? And that extended to all regex ?

Up to what point does these match (or don't) ?

On a side note, my man sed doesn't show the -E switch - but still works, and tells me the regex switch is -r. Are -E and -r the same thing ?

  • -r and -E do mean the same... regarding regex, it depends.. see https://unix.stackexchange.com/questions/119905/why-does-my-regular-expression-work-in-x-but-not-in-y .. – Sundeep Feb 23 '18 at 14:21
  • https://en.wikibooks.org/wiki/Regular_Expressions/POSIX-Extended_Regular_Expressions might help, but I'm not sure how true it is wrt to various implementations – Sundeep Feb 23 '18 at 14:21

1 Answers1

2

The manuals of both GNU grep and GNU sed mention -E as the option for using extended regular expressions:

grep:

-E --extended-regexp
Interpret the pattern as an extended regular expression (ERE). (-E is specified by POSIX.)

sed:

-E -r --regexp-extended
Use extended regular expressions rather than basic regular expressions.

(There's also a mention of -E being supported but undocumented earlier.)

You could check the exact definitions for the regexes supported by both, but your regex looks standard enough. In fact, it looks equivalent to the basic regex \$text *( *[^)] *) (unless your sed replacement uses the capture group).

However, do note that as written (in double-quotes) it will not match anything. The backslash will escape the dollar sign for the shell, preventing it from being treated as parameter expansion. But grep or sed will see a regex starting with $ for end of line. There can be nothing after the end of line, so the pattern cannot match. You need to add two more backslashes, or use single quotes instead of double quotes.

ilkkachu
  • 138,973