linux: emptying a file of its contents, without typing /dev/null

From when I first started working with Unix up to the nearly present, I had always used cat /dev/null to empty a file with a minimum of mess, i.e.,:
foozbear% cat /dev/null > big_useless_log

This, of course, made big_useless_log empty, and did so without getting rid of it, in case an a data write was imminent. If memory serves, this was all very consistent with the Unix principle of “First, Do no harm,” or, “Don’t make waves if you don’t have a board,” or whatever it was. (I believe using /dev/null in this way was called data lavage.)

This week I was using a lot of temp files — actually using the same temp file over and over to hold data I’d scraped from Cisco switch output so I could point some ‘awk’ at it for parsing purposes. For some reason, I decided to see what would happen if instead of removing and recreating the file (or more laboriously, typing cat /dev/null > temp), I used a redirection symbol, i.e.,
foozbear% > temp
Well, this worked as well as my previous steps, so I started alternating (using the command line up arrow) between my temp file resetting/editing
foozbear% > temp && vi temp
and my grep/awk line:
foozbear% egrep 'Gig|Fas' temp | awk '{print "interface "$2" "$3"\n description "$1}'

This worked fantastically (note that I was using bash under Ubuntu here), and a good time was had by all (the Cisco switches were particularly pleased, having their cdp output turned into port descriptions so handily — but perhaps I’ll expand on that later).

The redirection symbol also can be used if you are too lazy to create an empty file using ‘touch’. Instead of
foozbear% touch newfile
just type
foozbear% > newfile
and you’re all set.

Tags: , , , , ,