>_ IzzyLab

Hands-on task

This task is step 16 of the course “sed: the stream editor”

sed: reverse the order of lines

hard~7 min

Reverse the order of lines in the file /root/in.txt (the last line becomes the first, like tac does) and write the result to /root/out.txt. The goal is to do it in sed via the hold space; keep tac for checking yourself.

What you'll practise:
  • sed
  • hold space
  • pattern space
  • sed -n
  • address of the last line

Topic breakdown

Besides the main line buffer (the pattern space), sed has a second buffer — the hold space, where you can accumulate data between iterations over the lines. The commands for exchanging data between the buffers (copying into the hold, appending the hold to the pattern), the last-line address $ and address negation ! ("except") let you build up the result gradually. The reversal idea is to accumulate the lines so that each new one ends up before what's already accumulated, and to print the result once at the end; the -n flag disables the extra auto-print.

What's checked

  1. lines are reversed

What it looks like