Gus
Gus

Reputation: 251

Searching a file for the last match of a regexp in bash

I'm awful at bash and need to write a script to find the last instance of a regexp in a .log file. and return the entire line. Is this possible with sed or would I have to use awk?

Thanks!

Upvotes: 0

Views: 96

Answers (2)

drvtiny
drvtiny

Reputation: 715

Do it so:

sed -nr '/YOUR_REGEXP/h; ${g;p}' INPUT_FILE

grep will consume your memory by storing absolutely useless data: you dont need all matches except of last but it will be stored in memory, but only last of occurences/matches will be printed by tail -n1. And yes, GNU sed is faster then grep and support more complex regexp's.

Upvotes: 1

that other guy
that other guy

Reputation: 123410

Just find all matches with grep and get the last one with tail:

grep regex file | tail -n 1 

Upvotes: 1

Related Questions