Ryan
Ryan

Reputation: 10111

Grep match a word but not another word

I want to match a line with foo not followed by bar, e.g.

foo 123 <-- match
foo bar <-- not match

Using the following regex does not work:

echo "foo 123" | grep -E 'foo.*(?!bar).*'

Any idea?

Upvotes: 1

Views: 1168

Answers (3)

anubhava
anubhava

Reputation: 785266

On systems that don't have grep -P like OSX you can use this awk command:

awk -F 'foo' 'NF>1{s=$0; $1=""; if (!index($0,"bar")) print s}' file

Script Demo

Upvotes: 4

eminor
eminor

Reputation: 933

You can use -v to invert the match:

grep -v 'foo.*bar' file

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

You could try the below grep command which uses -P(perl-regexp) parameter,

grep -P 'foo(?:(?!bar).)*$' file

Example:

$ cat file
foo 123
foo bar
$ grep -P 'foo(?:(?!bar).)*$' file
foo 123

Or

use only negative lookahead to check whether the string bar is after to foo without matching any following character.

$ grep -P 'foo(?!.*bar)' file
foo 123

Upvotes: 3

Related Questions