Issue
Using sed
, I would like to print the last matching line of a file. I came across
sed: return last occurrence match until end of file
however, I would like only the matching line itself, not any range of lines. Using that page I actually came up with a working command
$ sed '/out_time=/h; $!d; x' progress.txt
out_time=00:00:07.720000
The question is why does this work, or to put another way what is going on in this command. Also include a simpler sed
command, if one exists.
Solution
It's simple, these are three independent commands run on each line (cycle):
- the
h
command replaces the current hold buffer with each line containingout_time=
. - the
$!d
deletes any line that isn't the last and restarts the next cycle. - the
x
command swaps the hold and pattern buffers.
The effect is that the final out_time=
line is placed in the hold buffer, and the only line that escapes through the $!d
filter (the last line of the file) is swapped with that hold buffer before printing.
Think of it as a program along the following lines:
for every line in file:
if line contains "out_time=":
holdbuff = line
if line is not last line of file:
continue for loop
swap line and holdbuff
print line
Of course, the whole tortured process can be avoided if you have the right tools for the job:
grep 'out_time=' progress.txt | tail -1
Answered By - paxdiablo Answer Checked By - Timothy Miller (WPSolving Admin)