Clearing file contents

Hi,

We need to clear the contents of a file. For this we tried using the commands like - '>filename' and 'cat filename > /dev/null'.

If the file size is large, the above commands will clear the file contents but the size of the file remains the same (checked using the command 'ls -l filename').

Are there any other UNIX commands which will empty the file contents?

Regards,
Raghavendra

`>filename` works for me on Solaris and Gentoo Linux (and I'm assuming every other Linux). Makes an empty, 0-byte file. The `cat filename > /dev/null` doesn't change the file since you are only catenating its contents and sending that output to /dev/null.

Hi,

Thanks for the reply...

But, as I mentioned earlier if the filesize is very large, say 500MB, then if I use the command ">filename", it will clear the file contents, but, when I do the "ls -l filename" it will will show the file size as 500MB itself, not as 0 bytes.

If the filesize is less, it will work without any problem.

It will be of great help, to get any other UNIX command which will clear the file contents.

Regards,
Raghu

>filename should work very well.

See this

[/tmp]$ dd if=/dev/zero of=/tmp/bigfile bs=1000 count=500000
500000+0 records in
500000+0 records out
[/tmp]$ ls -l /tmp/bigfile
-rw-r--r--    1 xxxxxxxx g900     500000000 May 22 00:11 /tmp/bigfile
[/tmp]$ >/tmp/bigfile
[/tmp]$ ls -l /tmp/bigfile
-rw-r--r--    1 xxxxxxxx g900            0 May 22 00:11 /tmp/bigfile
[/tmp]$ 

Since you notice the file size is still the same, it could be that some process is still using the file (?)

Use 'lsof' or 'fuser' to see what process is holding the file handler open.

Are there any other UNIX commands (apart from '>filename) which can be used to clear the file contents?

There is some command called shred which overrides file's contents, but it's not effective with many filesystems suchs as JFS, XFS, ReiserFS... and those which doesn't overwrite data in place.

Salut