Operating System - HP-UX
1752587 Members
4062 Online
108788 Solutions
New Discussion юеВ

Re: AWK: matching 2 or more Patterns

 
SOLVED
Go to solution
Alzhy
Honored Contributor

AWK: matching 2 or more Patterns

I would like to match 2 or more patterns being passed to AWK out of the sream passed to it.

With 1 stream:

someprog | awk F: '/pattern1/ {print $3}'

What if I have 2 or more patterns? Is it possible so I do not resort to multiple awk lines?

TIA... sorry I am getting rusty with the Shell and its utils.
Hakuna Matata.
6 REPLIES 6
James R. Ferguson
Acclaimed Contributor
Solution

Re: AWK: matching 2 or more Patterns

Hi:

Consider:

# X="line-1 ok\nline-2 not ok\nline-3 ok"
# echo ${X}|awk '/line-1|line-3/ {print}'
line-1 ok
line-3 ok

Regards!

...JRF...

Dennis Handly
Acclaimed Contributor

Re: AWK: matching 2 or more Patterns

>What if I have 2 or more patterns?

Besides JRF's ERE, you can use multiple patterns with ||:
'/line-1/ || /line-3/ { print }'
Hakki Aydin Ucar
Honored Contributor

Re: AWK: matching 2 or more Patterns

maybe egrep can be used according to your case:

# echo $output | egrep 'pattern1|pattern2|pattern3'
Dennis Handly
Acclaimed Contributor

Re: AWK: matching 2 or more Patterns

>Hakki: maybe egrep can be used according to your case:

Why? The whole purpose of a pattern in awk is to not use an extra grep process.
And using the "|" in egrep is the same as "|" in awk.
But if you want to use grep, don't use the egrep hammer for this simple case, use multiple "-e patterns".
Hakki Aydin Ucar
Honored Contributor

Re: AWK: matching 2 or more Patterns


>Why? The whole purpose of a pattern in awk is to not use an extra grep process.

Do you mean with extra grep usage here will affect runtime ? awk will work faster ?

>And using the "|" in egrep is the same as "|" in awk.

I know , just wanted to show alternative way. .

>But if you want to use grep, don't use the egrep hammer for this simple case, use multiple "-e patterns".

Yes, I know grep -E 'pattern1|pattern2' == egrep 'pattern1|pattern2' .
And you prefer grep in case of egrep not available in the system or what ? Can you explain Dennis ?

Regards.
Dennis Handly
Acclaimed Contributor

Re: AWK: matching 2 or more Patterns

>Hakki: Do you mean with extra grep usage here will affect runtime? awk will work faster?

Possibly. If invoking awk anyway, why add a grep.

>And you prefer grep in case of egrep not available in the system or what?

Instead of egrep's ERE, use grep's RE:
grep -e pattern1 -e pattern2