5

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.

HopelessN00b
  • 53,795
  • 33
  • 135
  • 209
pygorex1
  • 1,181
  • 2
  • 9
  • 10

6 Answers6

14

>output-file -- shortest possible version.

womble
  • 96,255
  • 29
  • 175
  • 230
2

This solution is more efficient than cat, because it doesn't create a subprocess (in addition to the shell process):

true >output-file
pts
  • 435
  • 1
  • 5
  • 16
2

You may do easy :)


:>output-file
Ali Mezgani
  • 3,850
  • 2
  • 24
  • 36
0

There is also:

truncate --size 0 file

Available from gnu coreutils (and probably others too).

I think it reads better than >file, and truncate also have more options (see truncate --help).

Ezbob
  • 101
0

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.

Evan Anderson
  • 141,881
  • 20
  • 196
  • 331
0

echo -n > YOURFILE
will remove file contents and keep the file, structure and permission intact.