Next: , Previous: head, Up: Examples

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//

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
     2,10 {; H; g; }

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.