megamence
megamence

Reputation: 355

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?

Upvotes: 5

Views: 2027

Answers (2)

Timur Shtatland
Timur Shtatland

Reputation: 12347

Use find -exec like so:

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

SEE ALSO:
GNU find manual

Upvotes: 2

anubhava
anubhava

Reputation: 785246

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.

Upvotes: 3

Related Questions