How to Empty or Delete a Large File Content in Linux?

Operating SystemLinuxMCA

Usually a continuously growing files, needs to be emptied from time to time to accept the latest data from the next operation. There are various mechanisms to empty the file. We will see them one by one below. The common approach is the overwrite the target file by using > sign which should come from a source which is empty.

/dev/null

This is a common method where we output empty result and then redirect that result to the target file.

# Original file size
$ls-lt
-rw-rw-r-- 1 ubuntu ubuntu 2925 Jan 1 08:39 ref_file.txt
# Redirect the output from /dev/null
$ cat /dev/null > ref_file.txt
-rw-rw-r-- 1 ubuntu ubuntu 0 Jan 1 09:35 ref_file.txt

echo

The echo command with null out put can also make the target file empty.

$ls-lt
-rw-rw-r-- 1 ubuntu ubuntu 2925 Jan 1 08:39 ref_file.txt
$echo > ref_file.txt
$ls –lt
-rw-rw-r-- 1 ubuntu ubuntu 0 Jan 1 09:36 ref_file.txt

Using >

Just putting only a > just before the file name will make it empty. We can also use just a colon(:) to get the same result.

$ls-lt
-rw-rw-r-- 1 ubuntu ubuntu 2925 Jan 1 08:39 ref_file.txt
$ > ref_file.txt
$ls –lt
-rw-rw-r-- 1 ubuntu ubuntu 0 Jan 1 09:39 ref_file.txt

Using truncate

Using truncate command with the size option as 0 will make the target file empty.

$ truncate s -0 ref_file.txt
$ ls-lt
-rw-rw-r-- 1 ubuntu ubuntu 0 Jan 1 09:41 ref_file.txt

Using touch

$ touch ref_file.txt
$ ls-lt
-rw-rw-r-- 1 ubuntu ubuntu 0 Jan 1 09:45 ref_file.txt
raja
Published on 03-Jan-2020 11:17:23
Advertisements