Getting the last match in a file using grep

grepunix

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?

Best Answer

You could try

grep pattern file | tail -1

or

tac file | grep pattern | head -1

or

tac file | grep -m1 pattern