Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using grep with regular expression to filter out matches

Tags:

grep

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?

like image 814
Hortitude Avatar asked Dec 12 '08 20:12

Hortitude


People also ask

How do I use grep to filter out?

grep is very often used as a "filter" with other commands. It allows you to filter out useless information from the output of commands. To use grep as a filter, you must pipe the output of the command through grep . The symbol for pipe is " | ".

Can I use regex with grep?

The grep command (short for Global Regular Expressions Print) is a powerful text processing tool for searching through files and directories. When grep is combined with regex (regular expressions), advanced searching and output filtering become simple.

How do I exclude items from grep?

By default, grep is case-sensitive. This means that the uppercase and lowercase characters are treated as distinct. To ignore the case when searching, invoke grep with the -i option. If the search string includes spaces, you need to enclose it in single or double quotation marks.

How escape grep regex?

This is described in Regular Expressions (regexp). If you include special characters in patterns typed on the command line, escape them by enclosing them in single quotation marks to prevent inadvertent misinterpretation by the shell or command interpreter.


2 Answers

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.

like image 192
Adam Rosenfield Avatar answered Sep 19 '22 00:09

Adam Rosenfield


You need to escape the pipe symbol when -e is used:

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" 
like image 31
Jay Avatar answered Sep 19 '22 00:09

Jay