Wednesday, 9 December 2015

How to Perform Multiple Search (OR Operation) in GREP

There are instances where we need to perform multiple search (logical OR operation). This article explain how to search multiple patterns using grep command.

Input File: F_Data_File.txt
EMPID|EMPNAME|EMPDEPT|EMPSAL|LOCATION
10001|A1|HR|10000|USA
10002|A2|FIN|20000|USA
10003|A3|NSS|30000|IND
10004|A4|SEC|40000|USA
10005|A5|TECH|50000|IND
10006|A6|TECH|60000|IND
10007|A7|TECH|70000|IND


SYNTAX:
grep -E "<pattern1>|<pattern2>" FileName
$ grep -E "HR|FIN" F_Data_File.txt

[OR]

SYNTAX:
egrep "<pattern1>|<pattern2>" FileName

$ egrep "HR|FIN" F_Data_File.txt

As you see, egrep is exactly same as 'grep -E'

[OR]

Use multiple -e option in a single command to use multiple patterns for the or condition.

SYNTAX:
grep -e <pattern1> -e <pattern2> FileName
$ grep -e 'HR' -e 'FIN' F_Data_File.txt

[OR]

SYNTAX:
grep '<pattern1>\|<pattern2>' FileName
$ grep 'HR\|FIN' F_Data_File.txt

[\ is a escape character,  which tells grep that pipe is not the part of string ]

Output: In all the cases output will remain same as below:
10001|A1|HR|10000|USA
10002|A2|FIN|20000|USA



If you want to search for both HR and FIN in the input file irrespective of the case, the below will provide the required.(Though we have provided HR and FIN in small case. switch i will make sure case insensitive search)

$ grep -i -E "hr|fin" F_Data_File.txt

Output:

10001|A1|HR|10000|USA
10002|A2|FIN|20000|USA


Note: GREP switches are valid in all the above scenarios, you can use them according to your requirement.Please follow previous article How to Play With GREP Switches  on grep switches for more insights.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...