How to clear the contents of a file from the command line?

I have a log file that has a bunch of stuff in it that I don't need anymore. I want to clear the contents.

I know how to print the contents to the screen:

cat file.log

I know how to edit the file, line-by-line:

nano file.log

But I don't want to delete each line one at a time. Is there a way to do it in one command without destroying the file to do it?


Solution 1:

In bash, just

> filename

will do. This will leave you with an empty file filename.

PS: If you need sudo call, please consider to use truncate as answered here.

Solution 2:

You can use the user command : truncate

truncate -s 0 test.txt

("-s 0" to specify the size)

http://www.commandlinefu.com/commands/view/12/empty-a-file

Solution 3:

You could do this:

echo -n "" > file.log

Using > to write the (null) input from echo -n to the file.

Using >> would append the null input to the file (effectively doing nothing but touching it).

Solution 4:

: > file.log

Same as > filename in Bash, but works in more shells (credit). Redirects the output from the true builtin (which has no output) to filename.