Server Fault is a question and answer site for system and network administrators. 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

What's the best way of getting only the final match of a regular expression in a file using grep?

Also, is it possible to begin grepping from the end of the file instead of the beginning and stop when it finds the first match?

share|improve this question
up vote 30 down vote accepted

You could try

grep pattern file | tail -1


tac file | grep pattern | head -1
share|improve this answer
+1 beat me to it. :) – Matt Nov 1 '10 at 23:36
tac file | grep -m 1 pattern – Dennis Williamson Nov 2 '10 at 0:54
With the added constraint that I wanted to get the line number (grep -n) in the actual file, I think tac pretty much had to be avoided, unless I wanted to do some subtraction with wc -l. Otherwise tac with grep -m1 makes a lot of sense. – Nick M Jul 4 '14 at 18:48
I'd love to see a more performant version than this, since I am trying to search a 20GB file. – Jeff Sep 4 '15 at 17:56

I am always using cat (but this makes it a little longer way): cat file | grep pattern | tail -1

I would blame my linux admin course teacher at college who love cats :))))

-- You don't have to cat a file first before grepping it. "grep pattern file | tail -1" and is more efficient, too.

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.