user2792748
user2792748

Reputation: 67

unix match multiple patterns in different lines

If I have a unix file contains the following:

aaaa12
bbbb34
ssss56
qqqq78
oooo90
aaaa01
bbbb23

I want to search for different patterns in different lines. in the above example if i want to print the lines that contain the two patterns (aaaa) and (bbbb) the output should be:

aaaa12
bbbb34
aaaa01
bbbb23

In the same order as the original file What is the suitable unix command to do this

I tried egrep "aaaa | bbbb" but the output was:

aaaa12
aaaa01
bbbb34
bbbb23

Upvotes: 0

Views: 1423

Answers (3)

konsolebox
konsolebox

Reputation: 75588

The simplest form for that is to use two expressions with -e:

egrep -e aaaa -e bbbb file
fgrep -e aaaa -e bbbb file

Output:

aaaa12
bbbb34
aaaa01
bbbb23

Upvotes: 0

iamauser
iamauser

Reputation: 11489

This may work for you :

egrep "(aaaa|bbbb)" file

or you can use awk :

awk '/aaaa/||/bbbb/{print}' file

In both these cases, it searches for pattern "aaaa" or "bbbb" in the file and displays them as they are in the file. the brackets () in egrep is for grouping. More explanation on egrep regex can be found in here :

http://www.gnu.org/software/findutils/manual/html_node/find_html/egrep-regular-expression-syntax.html

Result is this :

$]egrep "(aaaa|bbbb)" file
 aaaa12
 bbbb34
 aaaa01
 bbbb23
  • EDIT

OP probably wants the output in a single line rather than multiple lines. For that, you can do :

egrep "aaaa|bbbb" file | awk '{printf $0" "}'

OR

awk '/aaaa/||/bbbb/{printf $0" "}' file

Result :

aaaa12 bbbb34 aaaa01 bbbb23

Upvotes: 1

Carsten Massmann
Carsten Massmann

Reputation: 28226

Try the following

grep "aaaa\|bbbb" file

now it really works.

Upvotes: 1

Related Questions