Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using grep for multiple search patterns

Tags:

grep

unix

Consider I have the following stream of data:

BODY1
attrib1:  someval11
attrib2:  someval12
attrib3:  someval13

BODY2
attrib1:  someval21
attrib2:  someval22
attrib3:  someval23

BODY3
attrib1:  someval31
attrib2:  someval32
attrib3:  someval33

I want to extract only attrib1 and attrib3 for each BODY, i.e.

attrib1:  someval11
attrib3:  someval13
attrib1:  someval21
attrib3:  someval23
attrib1:  someval31
attrib3:  someval33

I tried

grep 'attrib1\|attrib3', according to this site but that returned nothing. grep attrib1 and grep attrib2 do return data but just for the single pattern specified.

like image 970
amphibient Avatar asked Nov 28 '12 17:11

amphibient


People also ask

Can grep command be used for searching a pattern in more than one file?

grep command can be used for searching a pattern in more than one file.

How do I combine two grep commands?

Use "extended grep" and the OR operator ( | ). Yes, you're right.


1 Answers

grep -e 'attrib1' -e 'attrib3' file

From the man page :

-e PATTERN, --regexp=PATTERN
Use PATTERN as the pattern. This can be used to specify multiple search patterns, or to protect a pattern beginning with a hyphen (-). (-e is specified by POSIX.)

Edit : Alternatively , you can save patterns in a file and use the -f option :

aman@aman-VPCEB14EN:~$ cat>patt
attrib1
attrib3

aman@aman-VPCEB14EN:~$ grep -f patt test
attrib1:  someval11
attrib3:  someval13
attrib1:  someval21
attrib3:  someval23
attrib1:  someval31
attrib3:  someval33
like image 115
axiom Avatar answered Sep 29 '22 16:09

axiom