Paul Dixon
Paul Dixon

Reputation: 4257

grep Top n Matches Across Files

I'm using grep to extract lines across a set of files:

grep somestring *.log

Is it possible to limit the maximum number of matches per file? Ideally I'd just to print out n lines from each of the *.log files.

Upvotes: 12

Views: 11361

Answers (2)

jaypal singh
jaypal singh

Reputation: 77105

Here is an alternate way of simulating it with awk:

awk 'f==10{f=0; nextfile; exit} /regex/{++f; print FILENAME":"$0}' *.log

Explanation:

  • f==10 : f is a flag we set and check if the value of it is equal to 10. You can configure it depending on the number of lines you wish to match.

  • nextfile : Moves processing to the next file.

  • exit : Breaks out of awk.

  • /regex/ : You're search regex or pattern.

  • {++f;print FILENAME":"$0} : We increment the flag and print the filename and line.

Upvotes: 2

oHo
oHo

Reputation: 54561

To limit 11 lines per file:

grep -m11 somestring *.log

Upvotes: 23

Related Questions