imajeeth
imajeeth

Reputation: 11

grep recursive + backwords + last match

Here is what I want to achieve.

I want to search for a pattern recursively in sub-directories and return the last match in each file.

I tried

grep -r "UVM_INFO" run.*/mti.log | tail -n 1

But this returns only the last match in the last file it searched. However, I want the last match in every file where there is a match.

Upvotes: 1

Views: 146

Answers (3)

janos
janos

Reputation: 124724

Another variation on @Aaron's solution:

find run.*/mti.log -type f -exec sh -c 'grep UVM_INFO {} | tail -n 1' \;

It's shorter without the while loop, but it's less efficient because of spawning a new sh process for every file.

Upvotes: 0

Aaron Davies
Aaron Davies

Reputation: 1230

Here's a cleaned-up version of user1234424's solution.

I'm not 100% sure how grep -r treats symlinks, so the find might need a bit of adjustment for that, but this should be correct otherwise.

find run.*/mti.log -type f -print0 | while read -rd '' filename; do grep UVM_INFO "$filename"|tail -1; done

Upvotes: 1

Sandeep
Sandeep

Reputation: 60

You can do it this way:

echo " " > results
for filename in find $(run.*/mti.log)
do
    grep "UVM_INFO" $filename|tail -n 1  >> results
done

not sure about this search criteria for find - might need to be changed

Upvotes: 0

Related Questions