Wednesday, June 24, 2009

Truncating a File

You can make truncating a file harder than it needs to be.

I'm walking through Hal Pomeranz's older Command-Line Kung Fu postings, both because I know there'll be useful stuff and because he has some fun challenges.

His Episode #19 attacks zeroing out an existing file. The solutions suggested are

cat /dev/null > my_file
and

cp /dev/null my_file
(which is both shorter and works even if noclobber is set, to prevent accidentally overwriting pre-existing files with > ).

Both of these are more typing than necessary. This works just as well:
> my_file
and never even invokes a command. It's all done by the shell.

What's that? You're running with set -o noclobber ?

>| my_file
If you want to do it in fewer characters, you can omit the space. :-)

Cut! It's a wrap.

No comments: