0

One could use -v to exclude a single word from a file, but I'm wondering why the regex pattern ?! is not working with grep/egrep.

I was searching for a pattern to exclude a single word from my search in a file in atom editor and found this link. The ?! works perfectly in atom. In bash I had to turn off histexpand with set +H first, otherwise you get -bash: !xxx: event not found as !pattern searches the history. After that I tried stuff like echo "no" | grep "^(?!yes).*", but grep does somehow not recognize the ?! pattern - why is that so?

Kusalananda
  • 333,661
manifestor
  • 2,473

1 Answers1

4
$ echo "no" | grep -P '^(?!yes).*'
no

The expression is not a standard basic nor standard extended regular expression, but a PCRE, a "Perl compatible regular expression". GNU grep knows about these if you use the utility with its -P flag.

Putting the expression in single quotes (which you should do since it's a static string) additionally stops bash from recognizing the ?!yes as a history expansion pattern.

From the GNU grep manual:

-P, --perl-regexp

Interpret the pattern as a Perl-compatible regular expression (PCRE). This is experimental and grep -P may warn of unimplemented features.

From the bash manual (my emphasis):

Only backslash (\) and single quotes can quote the history expansion character, but the history expansion character is also treated as quoted if it immediately precedes the closing double quote in a double-quoted string.

Kusalananda
  • 333,661