get last line from grep search on multiple files

you can use find to execute commands too:

find . -name "<file-name-to-find>" -exec grep "<pattern-to-match>" "{}" ";" | tail -1

"{}" is the file name, take care with shell globing and expasion when writing the command


Sort has a uniq option that allows you to select just one line from many. Try this:

grep PATTERN FILENAMES* | tac | sort -u -t: -k1,1

Explanation: Grep will return one line for each match in a file. This looks like:

$ grep match file*
file1.txt:match
file1.txt:match2
file2.txt:match3
file2.txt:match4

And what we want is two lines from that output:

$ ???
file1.txt:match2
file2.txt:match4

You can treat this as a sort of table, in which the first column is the filename and the second is the match, where the column separator is the ':' character.

Our first pipe reverses the output:

$ grep match file* | tac
file2.txt:match4
file2.txt:match3
file1.txt:match2
file1.txt:match

Our second pipe to sort, says: pull out the first unique line (-u), where the key to group by is the first one (-k1,1, key from column 1 to column 1), and we split the data into columns with ':' as a delimiter (-t:). It will also sort our output too! And its output:

$ grep match file* | tac sort -u -t: -k1,1
file1.txt:match2
file2.txt:match4

for f in $(find . -name "FILE_NAME"); do grep PATTERN $f | tail -1; done

An alternative to this could be done with awk instead of grep. A Posix version would read:

awk '(FNR==1)&&s{print s; s=""}/PATTERN/{s=$0}END{if(s) print s}' file1 file2 file3 ...

Using GNU awk, you can use ENDFILE

awk 'BEGINFILE{s=""}/PATTERN/{s=$0}ENDFILE{if(s) print s}' file1 file2 file3 ...

Tags:

Unix

Shell

Grep