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  Linux Show Public IP from Terminal
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.

Centos Failed Update Kernel

Today I did a kernel update on my server with Centos 7 OS. At the end of the update process, I found a kernel...
habibzain
1 min read

Easy Fix Missing mirrorlist http://mirrorlist.centos.org on CentOS 7

When running yum update or command that utilize the yum system, errors similar to the following are produced: If you’re encountering issues with the...
habibzain
1 min read

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

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