Is negative look-behind supported in OSX grep?

Solution 1:

The default OS X grep only supports Basic and Extended Regular Expressions as defined in POSIX and explained under re_format(7) for OS X. These flavors do not support negative look-behind.

If you want more powerful regular expression syntax, combined with greps ability to search a directory recursively for a regex pattern, you should consider using ack, which is written in Perl and thus supports its regex syntax, including negative look-behind.

The equivalent with ack would be:

ack '(?<!notthis)butthis'

You can install ack through:

  • Homebrew with brew install ack
  • The module in Perl's CPAN
  • Download of the single executable file on the homepage

It's worth noting that GNU grep has a -P option to enable Perl compatible regex syntax, however it is not included with OS X – you can install it through Homebrew if you like with brew install grep. On Linux, it will be available by default.

If you're switching between Linux and OS X a lot, like I do, I'd recommend using GNU grep on OS X by default, or using ack as a grep replacement altogether.