Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple grep search/ignore patterns

Tags:

I usually use the following pipeline to grep for a particular search string and yet ignore certain other patterns:

grep -Ri 64 src/install/ | grep -v \.svn | grep -v "file"| grep -v "2\.5" | grep -v "2\.6"

Can this be achieved in a succinct manner? I am using GNU grep 2.5.3.

like image 485
Sridhar Ratnakumar Avatar asked Aug 31 '09 17:08

Sridhar Ratnakumar


People also ask

How do I exclude multiple items in grep?

Specify Multiple Patterns. The -e flag allows us to specify multiple patterns through repeated use. We can exclude various patterns using the -v flag and repetition of the -e flag: $ grep -ivw -e 'the' -e 'every' /tmp/baeldung-grep Time for some thrillin' heroics.

How do I ignore a grep pattern?

Exclude Words and Patterns 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 do I grep for multiple searches?

If you want to find exact matches for multiple patterns, pass the -w flag to the grep command. As you can see, the results are different. The first command shows all lines with the strings you used. The second command shows how to grep exact matches for multiple strings.


2 Answers

Just pipe your unfiltered output into a single instance of grep and use an extended regexp to declare what you want to ignore:

grep -Ri 64 src/install/ | grep -v -E '(\.svn|file|2\.5|2\.6)'

Edit: To search multiple files maybe try

find ./src/install -type f -print |\
    grep -v -E '(\.svn|file|2\.5|2\.6)' | xargs grep -i 64

Edit: Ooh. I forgot to add the simple trick to stop a cringeable use of multiple grep instances, namely

ps -ef | grep something | grep -v grep

Replacing that with

ps -ef | grep "[s]omething"

removes the need of the second grep.

like image 180
Rob Wells Avatar answered Oct 04 '22 15:10

Rob Wells


Use the -e option to specify multiple patterns:

grep -Ri 64 src/install/ | grep -v -e '\.svn' -e file -e '2\.5' -e '2\.6'

You might also be interested in the -F flag, which indicates that patterns are fixed strings instead of regular expressions. Now you don't have to escape the dot:

grep -Ri 64 src/install/ | grep -vF -e .svn -e file -e 2.5 -e 2.6

I noticed you were grepping out ".svn". You probably want to skip any directories named ".svn" in your initial recursive grep. If I were you, I would do this instead:

grep -Ri 64 src/install/ --exclude-dir .svn | grep -vF -e file -e 2.5 -e 2.6
like image 45
Flimm Avatar answered Oct 04 '22 13:10

Flimm