Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get last line from grep search on multiple files

Tags:

grep

shell

unix

I'm curently having some problem with a grep command.

I've found the way to only show the last line of a grep search :

grep PATERN FILE_NAME | tail -1 

I also find the way to make a grep search in multiple selected files :

find . -name "FILE_NAME" | xargs -I name grep PATERN name 

Now I would like to only get the last line of the grep result for each single file. I tried this :

 find . -name "FILE_NAME" | xargs -I name grep PATERN name | tail -1 

This returns me only the last value of the last file where I would like to have the last matching patern for every file.

like image 968
B.jour Avatar asked Feb 14 '13 22:02

B.jour


2 Answers

for f in $(find . -name "FILE_NAME"); do grep PATTERN $f | tail -1; done 
like image 114
Daniel Frey Avatar answered Oct 01 '22 04:10

Daniel Frey


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 
like image 35
Colin Curtin Avatar answered Oct 01 '22 06:10

Colin Curtin