View Single Post

   
  #6 (permalink)  
Old 02-15-2008, 05:44 PM
Bela Lubkin
 
Posts: n/a
Default Re: help with grep looking for cats and dogs

Brian K. White wrote:

> From: "Kevin Fleming" <kevintickle@gmail.com>


> > I've been searching high and low for how to grep for two different
> > strings at once, and I'm not sure that it can be done. Ideas?
> > I've got a bunch of files and I'm searching for ones that have both the
> > word "cat" and "dog" in them, not necessarily on the same line.
> > I've tried using something like this:
> >
> > find /tmp -exec grep -q -E "cat" {} \; -print
> >
> > but I can't seem to do both cat and dog at the same time.
> >
> > find /tmp -exec grep -q -E "cat.\dog" {} \; -print
> >
> > this is closer, but it only works if cat and dog are on the same line.


> find /tmp -type f |xargs fgrep -l cat |xargs fgrep -l dog
>
> or
>
> find /tmp -type f |xargs -n 1 awk
> '{if($0~"cat")C=1;if($0~"dog")D=1;if(C+D==2){print ARGV[1];exit}}'


Whoops... my response would only find files with both words on the same
line. It is not my usual habit to misread things like that. Oh well.

Both of your ways should work. I think `awk` will process this
equivalent code slightly more efficiently:

awk '/cat/ { C = 1 }
/dog/ { D = 1 }
C + D == 1 { print ARGV[1]; exit }'

> A more readable version of the same awk code, placed into a seperate script
> file
>
> cat myscript
> #!/usr/bin/awk -f
> if ($0~"cat") C=1
> if ($0~"dog") D=1
> if (C+D==2) {print ARGV[1] ; exit }


Almost ... you need to put braces around all the code:

#!/usr/bin/awk -f
{
if ($0~"cat") C=1
if ($0~"dog") D=1
if (C+D==2) {print ARGV[1] ; exit }
}

>Bela<

Reply With Quote