Using grep to only obtain first match in EACH file

Viewed 611

I have a bunch of output files labelled file1.out, file2.out, file3.out, ...,fileN.out.

All of these files have multiple instances of a string in them called "keystring". However, only the first instance of "keystring" is meaningful to me. The other lines are not required.

When I do grep 'keystring' *.out I reach all files, and they output every instance of keystring.

When I do grep -m1 'keystring' *.out I only get the instance when file1.out has keystring.

I want to extract the line where keystring appears FIRST in all these output files. How can I pull this off?

2 Answers

You can use awk:

awk '/keystring/ {print FILENAME ":", $0; nextfile}' *.out

nextfile will move to next file as soon as it has printed first match from current file.

Use find -exec like so:

find . -name '*.out' -exec grep -m1 'keystring' {} \;

SEE ALSO:
GNU find manual

Related