Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep Last n Matches Across Files

Tags:

grep

shell

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 to the last n matches from each file?

like image 529
Paul Dixon Avatar asked Jan 25 '12 23:01

Paul Dixon


People also ask

What is option in grep?

The grep utility searches the input files, selecting lines matching one or more patterns; the types of patterns are controlled by the options specified. The patterns are specified by the -e option, -f option, or the pattern_list operand.

What is grep in shell script?

In Linux and Unix Systems Grep, short for “global regular expression print”, is a command used in searching and matching text files contained in the regular expressions.


1 Answers

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 -1; done

Replace tail -1 -1 with N. (-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: Above soln will work fine with file names with spaces.

For N matches from the start of the file

grep -i -m1 create *.log

Replace -m1 1 with N.

like image 91
havexz Avatar answered Dec 13 '22 08:12

havexz