Search Multiple Words / String Pattern Using grep Command on Bash shell

How do I search multiple strings or words using the grep command? For example I’d like to search word1, word2, word3 and so on within /path/to/file. How do I force grep to search multiple words? How can I grep for multiple patterns on Linux, OS X, FreeBSD, or Unix-like system?

The grep command supports regular expression pattern. To search multiple words, use following syntax:

How do I grep for multiple patterns?

The syntax is:

  1. Use single quotes in the pattern: grep 'pattern*' file1 file2
  2. Use extended regular expressions: egrep 'pattern1|pattern2' *.py
  3. Use this syntax on older Unix shells: grep -e pattern1 -e pattern2 *.pl

Here are all other possibilities:
grep 'word1|word2|word3' /path/to/file
### Search all text files ###
grep 'word*' *.txt
### Search all python files for 'wordA' or 'wordB' ###
grep 'wordA*'''wordB' *.py
grep -E 'word1|word2' *.doc
grep -e string1 -e string2 *.pl
egrep "word1|word2" *.c


In this example, search warning, error, and critical words in a text log file called /var/log/messages, enter:
$ grep 'warning|error|critical' /var/log/messages
To just match words, add the -w option:
$ grep -w 'warning|error|critical' /var/log/messages
Use the egrep command and you can skip the above syntax to search three words:
$ egrep -w 'warning|error|critical' /var/log/messages
$ grep -e 'warning|error|critical' /var/log/messages
I recommend that you pass the -i (ignore case) and --color option as follows too:
$ egrep -wi --color 'warning|error|critical' /var/log/messages
Sample outputs:

Fig.01: Linux / Unix egrep Command Search Multiple Words Demo Output

To search all *.conf files under /etc/, enter:
# egrep -wi --color 'foo|bar' /etc/*.conf
To search recursively (including sub-directories) listed, run:
# egrep -Rwi --color 'foo|bar' /etc/

This entry is 3 of 7 in the Linux / UNIX grep Command Tutorial series. Keep reading the rest of the series:

  1. How To Use grep Command In Linux / UNIX
  2. Regular Expressions In grep
  3. Search Multiple Words / String Pattern Using grep Command
  4. Grep Count Lines If a String / Word Matches
  5. Grep From Files and Display the File Name
  6. How To Find Files by Content Under UNIX
  7. grep command: View Only Configuration File Directives

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.