tags:

views:

757

answers:

5

I have a list of patterns in a text file, for which I use bzgrep to match on multiple files:

for pattern in $(cat ~/patterns.txt); do echo $pattern; bzgrep -i $pattern *.bz2; done

How do I make bzgrep (grep) stop after the first match of the current pattern (I need it stop completely, not stop on the current file being grep'ed) and go on to the next pattern. I have read about "-m 1" parameter, but I think it only stops on the current file. Any ideas?

Thanks

+4  A: 

Pipe the output of the grep to head -n 1; that will pull (& pass on) the first line and ignore the rest (i.e. kill the source pipe).

MarkusQ
A: 

You may wish to use the -q (--quiet aka --silent) switch. Then check to see if the command completed successfully or not. This outputs nothing and stops searching immediately upon finding a match, and just returns success or failure.

Eddie
+2  A: 
for pattern in $(< ~/patterns.txt); do
  echo "$pattern"
  for i in *.bz2; do
    bzgrep -i "$pattern" "$i" && break
  done
done

You may wish to add a -H to grep to display filename:line rather than just line.

A: 

Here's an example:

for i in  ~/bin/*; do grep -m 1 lua $i /dev/null && break; done

The same works with bzgrep; after the first successful match you exit the loop.

Including /dev/null gets you the filename in case you have some sort of dinosaur grep that doesn't recognize the -H option.

Norman Ramsey
A: 

If you use ack, at http://betterthangrep.com/, you can use the -1 flag for exactly this reason.

Andy Lester