Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while grep multiple files, how do I stop after first match?

Tags:

grep

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

like image 324
bob Avatar asked Mar 30 '09 23:03

bob


People also ask

Does grep stop after first match?

It doesn't stop after N matches, it stops after N lines. This will cause grep to match multiple times on each line, which can be a problem when used with the -o flag, which prints each match on a new line.

How do I grep a bunch of files?

To search multiple files with the grep command, insert the filenames you want to search, separated with a space character. The terminal prints the name of every file that contains the matching lines, and the actual lines that include the required string of characters. You can append as many filenames as needed.

Can we grep in multiple files?

By using the grep command, you can customize how the tool searches for a pattern or multiple patterns in this case. You can grep multiple strings in different files and directories. The tool prints all lines that contain the words you specify as a search pattern.

What is option in grep?

The grep utility searches the input files, selecting lines matching one or more patterns; the types of patterns are controlled by the options specified. The patterns are specified by the -e option, -f option, or the pattern_list operand.


2 Answers

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).

like image 94
MarkusQ Avatar answered Oct 04 '22 11:10

MarkusQ


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.

like image 28
brian-brazil Avatar answered Oct 04 '22 11:10

brian-brazil