How to grep patterns read from a file

grep is an awesome tool that allows you to search for strings, nunbers and patterns of them, its usage can be quite complicated since it…

How to grep patterns read from a file
Photo by Andrew Ridley on Unsplash

grep is an awesome tool that allows you to search for strings, nunbers and patterns of them, its usage can be quite complicated since it has a very large number of command line options, but on each simplest form search is done this way, assume that we have the following file named data.txt

This is a simple example 
in a text file

Now running the following command which searches for lines contain This returns the found line

$ grep This data.txt 
This is a simple example

But what if we have a procedure that everyday appends new keywords and those keywords needs to be used as search patterns against a file? Lets see how we can do this in a very easy way!

Creating the patterns file

Create the following file and save it as patterns.txt

This 
cat

From this file each line will be used a search pattern vs the file we want to search for patterns

The -f option does the magic!

-f is the option that allows us to use a file as a search pattern source, it works like this

grep -f patterns.txt data.txt

And it returns the following since This exists in both files! isnt that cool?

$ grep -f patterns.txt data.txt 
This is a simple example

Things to note

grep is very versatile! common options like -i and -v works with -f , this allows to do neat tricks like, finding lines in data.txt that no pattern exists in patterns.txt , line in a text file was print because nor This or cat exists in data.txt

$ grep -v -f patterns.txt data.txt 
in a text file

What about regexes?

-f parameter works with regexes as well, update patterns.txt to match the following

This 
cat 
text [0-9]

Then update data.txt to match the following

This is a simple example 
in a text file 
text 9

Running again the grep command generates the following, text 9 printed because matches regex text [0-9]

$ grep -f patterns.txt data.txt 
This is a simple example 
text 9

Conclusion

grep is a powerful command, one very useful option is -f as we saw! this allows us to create powerful tools and scripts that can make our daily life easier! i hope you enjoyed this article!