(sed.info)tail
4.13 Printing the Last Lines
============================
Printing the last N lines rather than the first is more complex but
indeed possible. N is encoded in the second line, before the bang
character.
This script is similar to the `tac' script in that it keeps the
final output in the hold space and prints it at the end:
#!/usr/bin/sed -nf
1! {; H; g; }
1,10 !s/[^\n]*\n//
$p
h
Mainly, the scripts keeps a window of 10 lines and slides it by
adding a line and deleting the oldest (the substitution command on the
second line works like a `D' command but does not restart the loop).
The "sliding window" technique is a very powerful way to write
efficient and complex `sed' scripts, because commands like `P' would
require a lot of work if implemented manually.
To introduce the technique, which is fully demonstrated in the rest
of this chapter and is based on the `N', `P' and `D' commands, here is
an implementation of `tail' using a simple "sliding window."
This looks complicated but in fact the working is the same as the
last script: after we have kicked in the appropriate number of lines,
however, we stop using the hold space to keep inter-line state, and
instead use `N' and `D' to slide pattern space by one line:
#!/usr/bin/sed -f
1h
2,10 {; H; g; }
$q
1,9d
N
D
Note how the first, second and fourth line are inactive after the
first ten lines of input. After that, all the script does is: exiting
on the last line of input, appending the next input line to pattern
space, and removing the first line.
automatically generated by info2www version 1.2.2.9