Home > Linux Tricks > How to Truncate a File to Zero Length in Linux

How to Truncate a File to Zero Length in Linux

October 28th, 2008 Leave a comment Go to comments

Sometimes you need to truncate a file to zero bytes. For example you have a big file that contains various logs and its size is too big to open it easily. Of course, you can revome this file and touch it again. But this way you’ll have to deal with permissions and file ownership. There is a simple command that will truncate the file to zero length without affecting any permissions. Here it is:

:>filename

If the file already exists, it will be truncated to zero bytes, else this command will create an . This is great for truncating big log files, e,g. Apache logs.

  1. December 9th, 2008 at 02:10 | #1

    For those who find this syntax too cryptic here is one that is much more memorable and fluent:

    cat /dev/null > file_to_be_truncated

  2. admin
    December 9th, 2008 at 06:22 | #2

    Another excellent solution, didn’t think about it :)

  3. July 21st, 2009 at 15:29 | #3

    Awesome! I have no idea whats happening in the :> step, but this is much more elegant than the /dev/null approach also mentioned ;D

  4. February 25th, 2010 at 22:20 | #4

    What is the : at the front. What about just:

    > filename

  1. April 21st, 2011 at 18:59 | #1