Tuesday, March 4, 2008

Heads or Tails

If you want the beginning or end of a file, head and tail work fine.

Before head, I used sed. These two commands do the same thing:

$ sed 5q foo
$ head -5 foo
I don't know a convenient sed synonym for tail, which does several, non-trivial things.
$ tail -5 # last 5 lines of the file
$ tail -n +5 # all but the first 5 lines
$ tail -f # start with the last 10 lines of the file
# but keep on spitting out lines as they appear
I use tail -f all the time, for glancing at output that I've been saving, from long running processes.
$ make &> make.OUT &
... # do some other stuff
$ tail -f make.OUT
... # watch it for a minute, to see how it's progressing
$ # go back to other stuff
But what about the upside-down of tail -n +5? What if I want all but the last five lines of the file? I don't know how to do this without writing a program.
(If you do, tell me.)

An exception to this, at my fingertips, is "all but the last one line."

If I have a directory full of logs, and I want to get rid of all but the most recent, here's how:
$ ls -rt
three-days-ago
day-before-yesterday

yesterday
today
$ ls -rt | sed '$d'
three-days-ago
day-before-yesterday

yesterday
$ rm -rf $(ls -rt | sed '$d')
$ ls
today
Because rm -rf won't complain if you invoke it without arguments, this last idiom is idempotent: if there's only one file in the directory, it leaves it alone, so it's still safe to use.

No comments: