9

I need to delete all lines in a file, but leave essentially an empty file with no content and no lines. As best I know, one can do this:

rm file.txt 2> /dev/null
touch file.txt

However, is there a simpler, more canonical solution in BASH?

Village
  • 22,513
  • 46
  • 122
  • 163

3 Answers3

23

This is a pretty fast way I always use:

> file.txt

It completely empties the file and updates the modification time.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
10

You can use truncate.

truncate -s 0 filename
Kirby Todd
  • 11,254
  • 3
  • 32
  • 60
6

Another (brutal) way to empty a file would be the following:

cat /dev/null > filename
trikelef
  • 2,192
  • 1
  • 22
  • 39