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:

This worked for me:

> file.log
link|improve this question

65% accept rate
feedback

4 Answers

up vote 4 down vote accepted

In bash, just

> filename

will do.

This will leave you with an empty file filename.

link|improve this answer
feedback

you could always type this:

echo "" > file.log

not >> as this will append.

link|improve this answer
This will leave a space in there. – dmckee Jan 1 '10 at 1:58
2  
+1. "" > file.log if you don't want the space. – RJFalconer Jan 1 '10 at 2:18
I'm getting this: -bash: : command not found – Andrew Jan 1 '10 at 3:52
1  
should be echo " " > file.log, I believe. – Babu Jan 1 '10 at 4:13
fixed on both counts (missing echo, extra space) – quack quixote Jan 1 '10 at 4:56
show 1 more comment
feedback
$ rm file.log; touch file.log

or

$ cat > file.log

followed by control-d.

or...or...or...

Ah. Here is a single command version:

$ dd if=/dev/null of=file.log
link|improve this answer
2  
Thechickenmoo's suggestion of echo "" > file.log is better than the cat option you show, in this situation, tho there are others where cat is more appropriate. both use the same shell redirection to do the heavy lifting. – quack quixote Jan 1 '10 at 4:57
1  
You dont need to run the cat command. Just "> file.log" will do it. – camh Jan 1 '10 at 6:22
1  
@camh: +1, that's a trick i didn't know before. nice one. – quack quixote Jan 1 '10 at 12:42
feedback

One line at a time?

Try vi(m), the lovely text editor that can do anything. In this case, navigate to a line, press d (for delete), and d again (for line).

link|improve this answer
3  
If you want to get rid of the whole file in vim, with the cursor at the top of the document, typing d G (that's d, then shift-G) will delete the entire file (d for delete, G for end of the file). I prefer your method, though (it gives me more time to think about whether or not I REALLY want to trash the file). – Babu Jan 1 '10 at 4:19
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.