Post

Using grep to search for multiple entries

Using grep to search for multiple entries

The OR operator in grep is \| — which is easy to forget when you’re used to other regex flavours. This is the pattern for searching a file for multiple terms in a single pass, which is much more efficient than running grep multiple times and piping results.

  • Let us create a file and add a few entries to it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$ # add some data to a file
$ echo "123\n456\nabc\ndef\nghi\n" > test.txt

$ # view the file contents
$ cat test.txt
123
456
abc
def
ghi

$ # search for 123 using grep
$ grep '123' test.txt
123 

$ # search for ghi using grep
$ grep 'ghi' test.txt
ghi

Now what if we want to search for multiple entries at the same time

We want grep to search for 123 or def or 456, in this case:

The or operator in grep is \|

So the search string will look like

abc\|def\|456

1
2
3
4
$ grep 'abc\\|def\\|456' test.txt 
456
abc
def
This post is licensed under CC BY 4.0 by the author.