Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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

2 Answers 2

up vote 20 down vote accepted

You could try

grep pattern file | tail -1

or

tac file | grep pattern | head -1
share|improve this answer
    
+1 beat me to it. :) –  Matt Nov 1 '10 at 23:36
6  
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 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

 
discard

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.