Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print last matching line?

Tags:

bash

awk

Using awk, I would like to print the last matching line of a file. I would like only the matching line itself, not any range of lines. I can use a command like this

awk '/foo/' bar.txt

However this will print all matching lines, not just the last one.

like image 603
Zombo Avatar asked Nov 27 '22 22:11

Zombo


1 Answers

You can save the value in a variable and then print it after processing the whole file:

awk '/foo/ {a=$0} END{print a}' file

Test

$ cat file
foo1
foo2
foo3
4
5
$ awk '/foo/ {a=$0} END{print a}' file
foo3
like image 125
fedorqui 'SO stop harming' Avatar answered Dec 06 '22 20:12

fedorqui 'SO stop harming'