DEV Community

Ahmy Yulrizka
Ahmy Yulrizka

Posted on • Originally published at til.yulrizka.com

grep: using input file as pattern to search other file

Sometimes we need to use another file which contains a multiple line that
we want to use as input pattern

example:

You have a.txt

a
b
c
d
e
Enter fullscreen mode Exit fullscreen mode

And you want to search a, c, e.

This case you can create input.txt

a
c
e
Enter fullscreen mode Exit fullscreen mode

and use this command

grep -f -F input.txt a.txt
Enter fullscreen mode Exit fullscreen mode

If the input txt is a list of regex you can remove the -F option.

 -F, --fixed-strings
              Interpret PATTERNS as fixed strings, not regular expressions.
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
drhyde profile image
David Cantrell • Edited

This is an absolutely brilliant feature. I use it all the time to find all the lines in file A that aren't in (ie grep -v) file B. One caveat is that on some platforms (yes, I'm glaring at you #OpenBSD) the file of patterns can't be empty, so the script in which I use it does an echo nonsense-that-will-never-appear-in-the-real-world >> thefile before using it.