Grep Top n File Compatibility

I use grep to extract strings through a set of files:

grep somestring *.log

Is it possible to limit the maximum number of matches per file? Ideally, I would simply print n lines from each of the * .log files.

+5
source share
2 answers

To limit 11 lines in a file:

grep -m11 somestring *.log
+9
source

Here is an alternative way to simulate using awk:

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

Explanation:

  • f==10 : f - this is the flag we set, and check if it is equal to 10. You can configure it depending on the number of lines you want to match.

  • nextfile : Moves the processing of the next file.

  • exit :Coming out of awk.

  • /regex/ :You are searching for regexor pattern.

  • {++f;print FILENAME":"$0} : We increase the flag and print the file name and line.

+2

All Articles