Skip to content
shellhacks.dev
Text Processing

Match a Line Not Containing a Word with grep -P

Match lines that do not contain a word using the PCRE pattern ^(?!.*word) with grep -P. Leave out the anchor and the lookahead matches every line.

1 min read
Summarize in AI

You need a pattern that means "does not contain", for a tool that accepts a regular expression but has no invert flag.

Shell
printf 'foo\nbar\nfood\n' > f
grep -P '^(?!.*foo)' f
echo ---
grep -P '(?!foo)' f
Text
bar
---
foo
bar
food

(?!...) is a negative lookahead: it succeeds when the text after the current position does not match. Anchored with ^ and holding .*foo, it asks at the start of the line whether foo appears anywhere later, and passes only for bar. Without the anchor the lookahead is tried at every position, and some position in every line is not followed by foo, so all three lines match, as the second command shows. Lookaheads are described in pcre2pattern.

Plain POSIX and ERE patterns cannot express this, and grep -v foo is simpler where you control the command. Lookarounds need PCRE, which means grep -P on GNU systems, or the regex module and most scripting languages. Many editors, sed and awk do not support them.

Taggedgrepregex
Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.