rick
rick

Reputation: 1115

Using sed/awk to print lines with matching pattern OR another matching pattern

I need to print lines in a file matching a pattern OR a different pattern using or . I feel like this is an easy task but I can't seem to find an answer. Any ideas?

Upvotes: 35

Views: 115692

Answers (4)

Vijay
Vijay

Reputation: 67211

why dont you want to use grep?

grep -e 'pattern1' -e 'pattern2'

Upvotes: 12

SiegeX
SiegeX

Reputation: 140257

The POSIX way

awk '/pattern1/ || /pattern2/{print}'

Edit

To be fair, I like lhf's way better via /pattern1|pattern2/ since it requires less typing for the same outcome. However, I should point out that this template cannot be used for logical AND operations, for that you need to use my template which is /pattern1/ && /pattern2/

Upvotes: 45

lhf
lhf

Reputation: 72312

awk '/PATT1|PATT2/ { print }'

Upvotes: 9

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

Use:

sed -nr '/patt1|patt2/p'

where patt1 and patt2 are the patterns. If you want them to match the whole line, use:

sed -nr '/^(patt1|patt2)$/p'

You can drop the -r and add escapes:

sed -n '/^\(patt1\|patt2\)$/p'

for POSIX compliance.

Upvotes: 28

Related Questions