1748169 Members
4044 Online
108758 Solutions
New Discussion юеВ

Re: egrep question

 
SOLVED
Go to solution
Allanm
Super Advisor

egrep question

Hi!

I want to egrep for two different words in a single line using egrep.

lets say line is -

allan is a great man

egrep for allan and great in the same line else dont print that line.

Thanks,
Allan.
5 REPLIES 5
James R. Ferguson
Acclaimed Contributor
Solution

Re: egrep question

Hi Allan:

If you want and AND relationship where both strings match:

# echo "allan is a great man"|grep allan|grep great

...but if you want an OR (alternation) where only one string need match:

# echo "allan is a great man"|grep -E "allan|great"

Regards!

...JRF...
Steven Schweda
Honored Contributor

Re: egrep question

> # echo "allan is a great man"|grep allan|grep great

Two "grep" processes? Ptui. Make one
process work harder:

alp$ echo 'allan is a great man' | egrep -e 'allan.*great|great.*allan'
allan is a great man

alp$ echo 'a great man is allan' | egrep -e 'allan.*great|great.*allan'
a great man is allan

As usual, everything's complicated, and the
fine print may matter. Case? Distinct
words, or strings anywhere?

alp$ echo 'greater gallantry' | egrep -e 'allan.*great|great.*allan'
greater gallantry

Of course, if the order is known, then the
regular expression could be simplified.
Hein van den Heuvel
Honored Contributor

Re: egrep question

Heed Steven's advice.

>> I want to egrep for two different words in a single line using egrep.

Hmmm, why would one feel one should use 'egrep' (fill in any other forcibly chosen tool) if one, apparently, does not know it well enough?

This _might_ be better solved with AWK

$ awk '/allan/ && /great/' your-file.txt

or perl


$ perl -ne 'print if /allan/ && /great/' your-file.txt

more perl, written more silly ...

$ perl -ne '/allan/ && /great/ && print' your-file.txt

fwiw,
Hein.
Allanm
Super Advisor

Re: egrep question

great discussion!

Thanks guys

Allan.
Dennis Handly
Acclaimed Contributor

Re: egrep question

>I want to egrep for two different words in a single line using egrep.

Why would you want to use the egrep hammer if you can use grep instead?

>egrep for allan and great in the same line

You can use this if you don't want a grep pipeline:
grep -e "allan.*great" -e "great.*allan"