Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep Top n Matches Across Files

Tags:

grep

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.

like image 653
Paul Dixon Avatar asked Jan 25 '12 02:01

Paul Dixon


2 Answers

To limit 11 lines per file:

grep -m11 somestring *.log
like image 137
oHo Avatar answered Oct 19 '22 13:10

oHo


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.

like image 28
jaypal singh Avatar answered Oct 19 '22 14:10

jaypal singh