Here's a simple one. How do I truncate an existing file in linux? That is, how do I empty the contents of the file but keep the file. I can always delete the file then touch
it but I was wondering if there's a single command that'll get the job done.
5 Answers
>output-file
-- shortest possible version.
-
1accepted for shortness - btw what does the extra colon do in
:>output-file
?– pygorex1Dec 2, 2009 at 21:06 -
No idea; probably best to ask mezgani since he was the one who suggested it.– womble ♦Dec 2, 2009 at 21:26
-
-
-
@Xepoch: Thanks; I couldn't find it mentioned in
bash
(1), it's too common a character. I suspected it was something like that, though.– womble ♦Dec 2, 2009 at 22:06
This solution is more efficient than cat, because it doesn't create a subprocess (in addition to the shell process):
true >output-file
You may do easy :)
:>output-file
-
This is short and it works in all major shells I use (bash, dash, zsh, pdksh, tcsh).– ptsDec 2, 2009 at 22:31
-
I'm sure a harder-core *nix person will have a better idea, but I've always done:
cat /dev/null > output-file
To truncate files.
echo -n > YOURFILE
will remove file contents and keep the file, structure and permission intact.