awkgrep

Using grep to only obtain first match in EACH file


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?


Solution

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