Table of contents

Clear the content of a file from shell command

Linux Jun 07, 2020 Viewed 32 Comments 0

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 1

Using : > data.txt has the same effect.

$ : > data.txt

echo

Using > to write the (null) input from echo -n to the file.

$ echo -n > data.txt

cat

$ cat /dev/null > data.txt

cp

Similar to the cat command.

$ cp /dev/null > data.txt

truncate

truncate can be used to reduce or expand files to a specified size.

$ truncate -s 0 data.txt

-s 0 to specify the size.

Updated Jul 06, 2020