This post explains about grep command to find multiple strings or keyword from file. In Linux or Unix like operating system, the grep command utility is widely used.
Grep is a command-line utility for searching plain-text data sets for lines matching a regular expression. Grep was originally developed for the Unix operating system, but is available today for all Unix-like systems. Its name comes from the ed command g/re/p (globally search a regular expression and print), which has the same effect: doing a global search with the regular expression and printing all matching lines. (Definition reference from Wikipedia)
Find the multiple strings or keyword in file by using grep command
To find the multiple strings or keyword in a file by using grep command,use the below given syntax
grep [options] 'keyword1|keyword2|Keyword3|keyword-N' /path/file-name
The below given is our sample file with contents
linux@tuxworld:/tmp$ cat sample.txt Orange white blue Blue line black red Red Apple green leaves yellow violet pink rose linux@tuxworld:/tmp$
Now using grep command to find multiple keywords from file called sample.txt
linux@tuxworld:/tmp$ grep 'black|red' sample.txt black red linux@tuxworld:/tmp$
For Exact Keyword :
Use -w option for exact matching keyword ( Check
man grep for this option )
With -w option, I searched only for exact keyword means case sensitive. If you have noticed, the keyword blue and Blue exist in sample.txt file
linux@tuxworld:/tmp$ grep -w 'black|red|blue' sample.txt blue black red linux@tuxworld:/tmp$
For Non Case Sensitive Keyword :
Use -i option withe grep command to find multiple non case sensitive keywords.
In our sample.txt we have two keyword i.e Blue and blue . Now we want to search keyword with non case sensitive option. Whereas we will also search some other keyword in same grep command.
linux@tuxworld:/tmp$ grep -i 'blue|yellow|red|green' sample.txt blue Blue line red Red Apple green leaves yellow linux@tuxworld:/tmp$
Leave a Reply