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? What is the command to search multiple words in Linux?
The grep command supports regular expression pattern. To search multiple patterns, use the following syntax:
Examples
The grep command supports regular expression pattern. To search multiple patterns, use the following syntax:
How do I grep for multiple patterns?
The syntax is:
- Use single quotes in the pattern: grep 'pattern*' file1 file2
- Next use extended regular expressions: egrep 'pattern1|pattern2' *.py
- Finally, try on older Unix shells/oses: grep -e pattern1 -e pattern2 *.pl
Grep searching two words in a line
Here are all other possibilities for grep and egrep command:
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
Examples
In this example, search warning, error, and critical words in a text log file called /var/log/messages, enter:
To just match words, add the -w option:
Use the egrep command and you can skip the above syntax to search three words:
$ 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
How to find multiple strings in files?
Let us try a few more examples with additional options passed to the grep/egrep:
I recommend that you pass the -i (ignore case) and --color option as follows too:
$ 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
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/
Where options are as follows:
- -R : Recursive search
- -w : Match only words
- -i : Ignore case distinctions. In other words match FOO, foo, Foo and so on.
- --color : Surround the matched in color on the terminal. For example, display matched strings in colors.
No comments:
Post a Comment
Feel free to leave a comment! If you have any information that you think should be included, please do so here and I'll get it added in.