amphibient
amphibient

Reputation: 31368

Using grep for multiple search patterns

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.

Upvotes: 24

Views: 100849

Answers (6)

Jamilah Foucher
Jamilah Foucher

Reputation: 21

Also, if there are multiple patterns be sure to put e option as the last options. For example,

grep -iwe 'the' -e 'that' -e 'then' -e 'those' text

OR

grep -iwe 'the' -iwe 'that' -e 'then' -e 'those' text OR grep -wie 'the' -wie 'that' -wie 'then' -wie 'those' text

works! But, if you put e first, like

grep -eiw 'the' -e 'that' -e 'then' -e 'those' text

it returns an error.

Upvotes: 0

SteveScm
SteveScm

Reputation: 565

Very simple command:

 bash> grep  "attrib1\|attrib3" <file.name>
attrib1:  someval11
attrib3:  someval13
attrib1:  someval21
attrib3:  someval23
attrib1:  someval31
attrib3:  someval33

Upvotes: 23

Mike Makuch
Mike Makuch

Reputation: 1838

Also egrep;

egrep "pattern1|pattern2|pattern3" file

Upvotes: 19

Siva
Siva

Reputation: 9

It depends on the shell you are into. grep -iw 'patter1\|patter2\|pattern3' works on bash shell where as it doesn't work on korn shell. For korn shell we might have to try grep -e pattern1 -e patter2 and so on.

Upvotes: 0

Sirch
Sirch

Reputation: 417

This works, with GNU grep 2.6.3

grep "attrib[13]"

or

 grep "^[^0-9]*[13]:"

Upvotes: 1

Aman
Aman

Reputation: 9035

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

Upvotes: 33

Related Questions