Clear the content of a file from shell command
In Linux/Unix, there are several ways to clear the contents of the file with the shell command.
> filename
With the > filename command to create a file if the file does not exist. If the file exists, it will clear all contents of the file.
$ > data.txt
$ echo '' > data.txt
$ echo 'line 1' >> data.txt
$ cat data.txt
line 1Using : > data.txt has the same effect.
$ : > data.txtecho
Using > to write the (null) input from echo -n to the file.
$ echo -n > data.txtcat
$ cat /dev/null > data.txtcp
Similar to the cat command.
$ cp /dev/null > data.txttruncate
truncate can be used to reduce or expand files to a specified size.
$ truncate -s 0 data.txt-s 0 to specify the size.