Monday, April 6, 2009

Episode #19 - Clearing The Contents Of A File

Paul Writes In:

Ever want to delete just the contents of a file, but not the file itself? There are many ways to do this on UNIX/Linux systems, here's one:

$ cat /dev/null > my_file

Probably the most common usage for this is to clean out a log file. I'm certain Hal will have several suggestions, and Ed will have to (again!) be creative without /dev/null in Windows :)

Hal Says:

I generally "set -o noclobber" in my .bashrc because I don't want to accidentally overwrite files with output redirection (and you should too, Paul!). Thus, Paul's command line above is not as useful for me. My idiom is usually just:

$ cp /dev/null my_file

It's also two characters (not counting extraneous spaces) shorter than Paul's version. Go me!

Ed Responds:

While we don't have /dev/null in Windows, we do have the very handy nul, the rough equivalent of /dev/null. I use it rather often to make things go away, usually directing unwanted Standard Out to it. But, to delete the contents of a file, you could use nul like this:

C:\> type nul > my_file

This will keep the file's creation time (viewable with "dir /tc my_file", as we discussed in Episode 11), while making the contents of the file empty.

Alternatively, we can remove the contents of a file in Windows using Hal's approach of copying with:

C:\> copy nul my_file

Oh, and my copy command is four less characters less to type than Hal's fu above, a whopping six characters less than Paul's. Efficiency, thy name is Windows. Go Windows! Now there's something that you don't hear often in a battle of the command shells!

BTW, thanks for the "set -o noclobber" tip, Hal. Very useful! Almost always in my SANS 560 class, attendees accidentally hose their systems by flipping a <> and destroying /etc/passwd or /etc/shadow on their Linux boxen, even though I warn them about it. I'll set noclobber by default for their shells, which should prevent that from happening, but will introduce frustrations when their bad command doesn't work. I guess the frustration is better than hosing the system.

And, the hits just keep on coming...