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
You can assign values to variables and print them at the end of processing both the lines and their number.
File:
$ cat file
foo1
foo2
foo3
4
5
Command:
$ awk '/foo/ {a=$0;n=NR} END{print n, a}' file
3 foo3
The command tail
allows you to retreive the last n
lines of an input stream. You can pipe your awk
output into tail
in order to trim off everything except the last line:
awk '/foo/' bar.txt | tail -1
sed
solution:
sed -n '/foo/h;$!b;g;p' bar.txt
Place the matching regex
in hold buffer and branch out. Keep doing this until end of file. When the end of file is reached, grab the line from hold space and place it on pattern space. Print pattern space.
reverse the file and find the first match.
tac file | awk '/foo/ {print; exit}'
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
$ cat file
foo1
foo2
foo3
4
5
$ awk '/foo/ {a=$0} END{print a}' file
foo3