Grep Multiple Strings or Patterns from a Text File in Linux
There are several ways you can match multiple strings or patterns from a file using grep. As with everything in Linux, there are several ways to accomplish the same task. Here we will discuss pattern matching, basic regular expressions and extended regular expression. This is not meant to be a regex primer, but they are an important tool for matching several patterns.
Using Pattern Matching to Grep Multiple Strings
You can specify several patterns by using the -e switch.
grep -e Pattern1 -e Pattern2 filename
Here is an example of searching for the word winced, and the word motion, in the text of the Harrison Bergeron short story that is saved as HarBerg.txt.
grep -e "winced" -e "motion" HarBerg.txt
Using Basic Regular Expressions to Grep Multiple Strings
The grep command supports both basic and extended regular expressions. Here is an example of using basic regular expressions to find two strings in a file using grep.
grep 'Pattern1\|Pattern2' filename
Basic regexp do not support the pipe ( | ) as an OR operator, so we have to escape it with a backslash.
Here we will use the same patterns and text file as above, but using the basic regular expressions syntax.
grep 'motion\|winced' HarBerg.txt
Using Extended Regular Expressions to Grep Multiple Strings
Extended Regular Expressions support the OR operator. We can use the extended regexp by using the -E option with grep.
grep -E 'Pattern1|Pattern2' filename
or, we can use egrep:
egrep 'Pattern1|Pattern2' filename
In extended regexp we do not need to escape the pipe because it is supported as an OR operator.
egrep 'winced|motion' HarBerg.txt
You can set an alias for grep to egrep for convenience.
There are always several ways to accomplish the same task in Linux. Some people find certain ways easier to remember, or just more efficient. Here we examined three different ways to grep multiple strings from a file, pattern matching, basic regular expression and extended regular expressions. They all achieved the same results, but done in a different way.
If you know of an different method feel free to post them in the comments. I love input from our visitors.
This site uses Akismet to reduce spam. Learn how your comment data is processed.