Thursday, May 25, 2023
HomeSoftware EngineeringThe best way to Match A number of Strings with grep

The best way to Match A number of Strings with grep


If you want to match a string in a file, then grep is your pal.

An instance of utilizing grep

Let’s take a file referred to as somefile.txt

this
is
a
check
that
appears to be like
for
one thing

We are able to search for the string one thing on this file utilizing grep:

cat somefile.txt | grep one thing
# one thing

However what if we wish to search for each one thing and this?

An instance of utilizing a number of greps

It’s fairly simple, we simply go the -E flag, which is brief for --extended-regexp, and separate our strings with a pipe |.

cat somefile.txt| grep -E "one thing|this"
# this
# one thing

All of the methods to make use of grep a number of patterns

Multiples:

grep 'word1|word2|word3' /path/to/file

Search all textual content information:

grep 'phrase*' *.txt

Search all python information for wordA and wordB:

grep 'wordA*'''wordB' *.py
grep -E 'word1|word2' *.doc
grep -e string1 -e string2 *.pl
egrep "word1|word2" *.c

Present all of the traces that don’t match given sample/phrases/strings:

grep -v 'bar|foo' /dir1/dir2/file1
egrep -v 'pattern1|pattern2' /path/to/file
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments