7

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.

0

5 Answers 5

32

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome solution!
6

reverse the file and find the first match.

tac file | awk '/foo/ {print; exit}' 

3 Comments

This assumes that no earlier context is required in order to determine which lines to print.
Hmm, just occurred to me you could also do this with tac file | grep -m1 foo so that MAY be slightly better as it's briefer and IMHO no less clear. Won't work with all greps though, it might be GNU grep specific.
tac $file | grep $pattern | tac | tail -n $N -- to print last N matched lines preserving order
6

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.

Comments

5

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 

1 Comment

Without a pipe, store the line and print it in END.
3

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.