Re: help with grep looking for cats and dogs jdanskinner wrote:
> Bela Lubkin wrote:
> > 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<
>
> Simple and crude but easy:
> grep -l dog `grep -l cat /tmp/*`
> or
> grep -l dog /tmp/* | xargs grep -l cat
> or if you must find
> find /tmp -name "*" -exec grep -l dog {} \; | xargs grep -l cat
>
> Regards...Dan.
Thanks to everyone for their help on this. I'm stilll learning how
scripts and the syntax works...
Brian's suggestion:
find /tmp -type f |xargs fgrep -l cat |xargs fgrep -l dog
was the simplest for me to understand, even if it wasn't the most
efficient. I promise to spend some time learning about shell scripts,
and I appreciate the explanations with the examples.
Thanks again,
Kevin |