11

I'm trying to do something like this:

grep -r '(?<!notthis)butthis' ./*

And I'm getting no results when some should be returned. Am I missing an escape? Or does OSX just not support regex lookaround?

1 Answer 1

21

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:


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.

1
  • It is worth mentioning that the version of ack installed via Homebrew does not support variable length lookbehind (e.g. find . | ack 'node_modules(?<!.*node_modules)'). Commented Oct 9, 2015 at 23:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .