tags:

views:

2078

answers:

2

I'm trying to use grep with -v for invert-match along with -e for regular expression. I'm having trouble getting the syntax right.

I'm trying something like

tail -f logFile | grep -ve "string one|string two"

If I do it this way it doesn't filter If I change it to

tail -f logFile | grep -ev "string one|string two"

I get

grep: string one|string two: No such file or directory

I have tried using () or quotes, but haven't been able to find anything that works.

How can I do this?

+7  A: 

The problem is that by default, you need to escape your |'s to get proper alternation. That is, grep interprets "foo|bar" as matching the literal string "foo|bar" only, whereas the pattern "foo\|bar" (with an escaped |) matches either "foo" or "bar".

To change this behavior, use the -E flag:

tail -f logFile | grep -vE 'string one|string two'

Alternatively, use egrep, which is equivalent to grep -E:

tail -f logFile | egrep -v 'string one|string two'

Also, the -e is optional, unless your pattern begins with a literal hyphen. grep automatically takes the first non-option argument as the pattern.

Adam Rosenfield
heh, learn something new every day, I never noticed the -E flag on grep before.
Jay
A: 

You need to escape the pipe symbol:

tail -f logFile | grep -ve "string one\|string two"

EDIT: or, as @Adam pointed out, you can use the -E flag:

tail -f logFile | grep -vE "string one|string two"
Jay
First part of the answer is inaccurate - and the second part is derivative.
Jonathan Leffler
I tested the first part on my system and it had the desired results. Not sure what you mean by inaccurate.
Jay