Home About RSS Email Subscription

Wednesday, June 13, 2007

Quick Tip: Delete the Contents of a File without Removing and Recreating It

I had to clear out some log files on one of the iminlikewithyou servers yesterday, but I didn't want to delete and recreate the files because I thought that might screw up permissions. I'd been meaning to learn how to zero out a file to empty contents for a while, so I took this opportunity to figure it out.

Do all this from the command line or terminal.

This will create a new file named t whose contents is the word "test":
$ echo "test" > t

more will display the contents of the file:
$ more t
test

Here's the new trick I learned. cat reads the contents of /dev/null (which contains nothing) and > writes this into t
$ cat /dev/null > t

Now t contains nothing:
$ more t

Get rid of it (don't do this to your logfile)
$ rm t

9 comments:

Matthew T. said...
This post has been removed by the author.
Matthew T. said...

Another, quicker, way is:

$ > file.txt

Just redirect 'nothing' to the file. It works under some shells. I think it works in bash, I know it doesn't work in tcsh.

Brian Jung Myeng said...

echo > something.txt

should work on all shells. :-)

Try less instead of more as well.

MikeDawg said...

Just like everyone else is saying, no need to bring /dev/null into the picture. A simple: > filename would work.

Although, I do find myself using echo "" > filename .

Alex said...

Not really sure (don't have Windows at the moment), but I think this would work:

copy nul > file.txt

because I think nul is a special file in Windows, like con, lpt1 and others.


As a related tip, you can quickly create files from the command-line in Windows:

copy con > file.txt

and type away, then press Ctrl-Z and Enter to save the file.

kortina said...

Cool, thanks for all the tips, fellas. I especially like the bash version:

$ > file.txt

Rob said...

The null redirect is a ksh-ism, whence its appearance in bash.

> file

Anonymous said...

For the echo variants, you need:

echo -n "" > t
or
echo -n > t

to avoid writing a newline byte.

> t

works fine as is.

Gary said...

On Windows,

rem > filename

Will result in a zero-byte file