1753468 Members
4408 Online
108794 Solutions
New Discussion юеВ

Re: egrep and patterns

 
Leo The Cat
Regular Advisor

egrep and patterns

Hi


I know to use egrep like this for the OR
egrep -i '(65535|65536)'

How to do the same thing but with AND

Any Idea


Bests Regards
Den
10 REPLIES 10
Leo The Cat
Regular Advisor

Re: egrep and patterns

Ho sorry

precision: patterns are not in the same line !

Leo The Cat
Regular Advisor

Re: egrep and patterns

Here my input
a
b
c
d
e
test1
f
g
f
test2
h
h
j


I need to find if this input contains test1 AND test2 !!!

Ivan Ferreira
Honored Contributor

Re: egrep and patterns

Please refer to this thread:

http://forums13.itrc.hp.com/service/forums/questionanswer.do?admit=109447627+1244229489824+28353475&threadId=1320198
Por que hacerlo dificil si es posible hacerlo facil? - Why do it the hard way, when you can do it the easy way?
James R. Ferguson
Acclaimed Contributor

Re: egrep and patterns

Hi Den:

This is one way (if you insist on 'grep') but requires two passes of your input:

# grep -q test1 myfile && grep -q test2 myfile && echo "ok" || echo "no match"

A faster way would be to use Perl or awk like:

# perl -nle 'm/test2/ and $x=1;m/test1/ and $y=1;last if $x+$y==2;END{print $x+$y==2 ? "ok" : "nomatch"}' myfile

By the way, you have un-evaluated solutions in your earlier thread:

http://forums.itrc.hp.com/service/forums/questionanswer.do?threadId=1344958

Feedback there too is appreciated :-)

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: egrep and patterns

Hi (again) Den:

In the event that you want more than a "yes/no" answer to the presence of the AND'ed match (as I provided in the first solutions, above) you could use:

# grep -q test1 myfile && grep -q test2 myfile && grep -E "test1|test2" myfile

...which again "suffers" from multiple passes through the file.

...OR in one pass of the file:

# perl -nle 'm/test1/ and $x=1,push(@a,$_),next;m/test2/ and $y=1,push(@a,$_),next;END{if ($x&&$y) {print for (@a)}}' myfile

Regards!

...JRF...
ghostdog74
Occasional Advisor

Re: egrep and patterns

you just use awk

awk '/test1/{s[FNR]=$0}/test2/{f=1;s[FNR]=$0}END{if (f){for(i in s) print s[i]}}' file
Dennis Handly
Acclaimed Contributor

Re: egrep and patterns

>patterns are not in the same line

You can use multiple passes of grep like JRF said:
grep test1 $(grep -l test2 file-list)
emha_1
Valued Contributor

Re: egrep and patterns

Hi,

what about simple:

grep -e test1 -e test2


emha.
ghostdog74
Occasional Advisor

Re: egrep and patterns

>grep -e test1 -e test2

if file only has test1 and not test2, then it will not work.