## Get N matches using grep

by paramvir aka havexz on Feb.11, 2012, under Programming

Here is the test data that we gonna use:

>grep create *.log 1.log:create1 1.log:create2 10.log:create1 10.log:create2 2.log:create1 2.log:create2 3.log:create1 3.log:create2 4.log:create1 4.log:create2 5.log:create1 5.log:create2 6.log:create1 6.log:create2 7.log:create1 7.log:create2 8.log:create1 8.log:create2 9.log:create1 9.log:create2 >

**Finding the First N matches**

For N matches from the start of the file

grep -i -m<N> create *.log

Example:

>grep -m1 create *.log 1.log:create1 10.log:create1 2.log:create1 3.log:create1 4.log:create1 5.log:create1 6.log:create1 7.log:create1 8.log:create1 9.log:create1 >

**Finding the Last N matches**

Well I think grep does not support to limit N matches from the end of file so this is what you have to do.

ls *.log | while read fn; do grep -iH create "$fn" | tail -<N>; done

Example:

>ls *.log | while read fn; do grep -iH create "$fn" | tail -1; done 1.log:create2 10.log:create2 2.log:create2 3.log:create2 4.log:create2 5.log:create2 6.log:create2 7.log:create2 8.log:create2 9.log:create2 >

(-H options is to print the file name else it wont be printed if you are grep in a single file and thats exactly we are doing above)

NOTE: The above soln will cover file names with ‘spaces’ but if filenames include unicode, newline etc. it might now work.

*:*grep, script, shell