Luke Oliff.

TIL: Using grep -P for Perl-Compatible Regex in the Terminal

·TIL·1 min read·Luke Oliff

grep is the swiss army knife of text search. The -P flag gives it full Perl regex syntax.

grep -P '(?<!\w)error(?!\w)' server.log

The lookbehind and lookahead match “error” but not “errors” or “terror”. Standard grep cannot check context around a match.

grep -P '\b(?:warning|error|critical)\b' app.log

The non-capturing group matches any of three words. The word boundaries exclude partial matches.

grep -P '^.{100,}$' long-lines.txt

Match lines with 100 or more characters.

Does grep -P work on macOS?

macOS uses BSD grep which does not support -P. Install GNU grep with brew install grep and use ggrep -P.

What about performance?

Perl compatible regex is slower. For large files use grep -E first and -P only when you need lookarounds.