habibzain Just husband, father and enthusiastic men about System Administration. Love to write short article about it. Perhaps can help and be useful for others.

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

51 sec read

Search-Multiple-Words string

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/fill

### 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:

$ 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

OR

$ 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
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/

source : https://www.cyberciti.biz/faq/searching-multiple-words-string-using-grep/

See also  Fix Package gnupg2 is not installed
habibzain Just husband, father and enthusiastic men about System Administration. Love to write short article about it. Perhaps can help and be useful for others.

Easy Create Laravel Project with Composer

Requirement Laravel, a popular PHP framework, is renowned for its elegant syntax and robust features, making it a top choice for web developers. One...
habibzain
1 min read

Virtualbox Change Storage Size

Changing the storage size of a virtual machine in VirtualBox involves a few steps. Here’s a general guide. Backup your Virtual Machine (VM) Before...
habibzain
35 sec read

Easy Setup Logrotate Nginx Ubuntu

Log rotation is an important aspect of managing log files on a Linux system, including those generated by Nginx. Logrotate is a utility that...
habibzain
1 min read

Leave a Reply

Your email address will not be published. Required fields are marked *

Never miss good article from us, get weekly updates in your inbox