How to empty a file without deleting and recreating it?

Was working with log files and wanted a quick way to empty them and recreate them. rm and touch would do it, but found something simpler:

CODE:
  1. cat /dev/null > filename

As simple as that!

 

8 comments ↓

#1 Atul on 09.17.07 at 11:14 pm

Try

echo -n > file
:)

#2 VaibhaV Sharma on 09.18.07 at 5:17 am

try

echo > filename

#3 Tejas Dinkar on 09.18.07 at 8:19 am

Try

> filename

Yes, I get shortest command prize :D

#4 James Urquhart on 09.18.07 at 3:20 pm

Wow.

I’m in awe. I’ll have to remember these next time i am working with log files and such! :)

#5 alephnull on 09.18.07 at 4:29 pm

:> is the POSIX way, iirc. The dummy placeholder : makes it work on some shells where a plain > doesn’t.

#6 Kartik Mistry on 09.18.07 at 6:13 pm

cat has supercow power!

cat /dev/cdrom > foo.iso to create iso from cdrom ;)

#7 aamod on 09.18.07 at 9:01 pm

you can also use

cat > [the filename u want to clear]

Press Ctrl D..
You’re done….

#8 VaibhaV Sharma on 09.18.07 at 11:57 pm

Ah, about the echo > filename, it will work on any shell as compared to the “> filename” but some apps don’t like the one newline character that echo leaves in the file. So edit the file with vi, dd the first line, save and you are done.

Leave a Comment