sed: tail

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