Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a bunch of files, I'd like to find the last match of a string in each of them.

grep text *.file gives me all the matches not the last ones.

ls *.file | xargs grep text | tail -n 1 gives me the last line of the last file that matches.

So what I think I want is a way to say:

ls *.file | (xargs grep text | tail -n 1)

But I'm not sure how to do this, or if it's possible.

share|improve this question
up vote 1 down vote accepted

Use tail -n 1 in a for loop. For example:

for name in *.file; do
    grep -H text "$name" | tail -n 1

(The -H option will make grep always print the file name, even if only one file was given.)

share|improve this answer

There is a oneliner over a tac commad, that output file from end till begin:

find . -name *.log -exec sh -c "tac '{}' | grep -Hm1 text " \;
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.