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

Continuously growing log files and data files often need to be emptied periodically to free up disk space while preserving the file structure. Linux provides several efficient methods to empty large files without deleting them entirely.

Using /dev/null Redirection

The most common method redirects empty output from /dev/null to overwrite the target file ?

# Check original file size
$ ls -lt ref_file.txt
-rw-rw-r-- 1 ubuntu ubuntu 2925 Jan 1 08:39 ref_file.txt

# Redirect empty output to file
$ cat /dev/null > ref_file.txt

# Verify file is now empty
$ ls -lt ref_file.txt
-rw-rw-r-- 1 ubuntu ubuntu 0 Jan 1 09:35 ref_file.txt

Using echo Command

The echo command with empty output can also empty the target file ?

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

$ echo > ref_file.txt

$ ls -lt ref_file.txt
-rw-rw-r-- 1 ubuntu ubuntu 1 Jan 1 09:36 ref_file.txt

Note: echo adds a newline character, so the file size becomes 1 byte instead of 0.

Using Redirection Operator Only

Simply using the redirection operator > before the filename will empty it instantly ?

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

$ > ref_file.txt

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

Using truncate Command

The truncate command with size option set to 0 effectively empties the file ?

# Truncate file to 0 bytes
$ truncate -s 0 ref_file.txt

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

Using touch Command

The touch command creates an empty file or empties an existing one ?

$ touch ref_file.txt

$ ls -lt ref_file.txt
-rw-rw-r-- 1 ubuntu ubuntu 0 Jan 1 09:45 ref_file.txt

Comparison of Methods

Method File Size Result Best For
cat /dev/null > 0 bytes Clear syntax, widely used
echo > 1 byte (newline) Quick emptying
> 0 bytes Fastest method
truncate -s 0 0 bytes Large files, precise control
touch 0 bytes Simple file reset

Conclusion

Use > filename for the fastest file emptying. Use truncate -s 0 for large files where performance matters. The cat /dev/null > method is most readable and widely understood.

Updated on: 2026-03-15T17:24:18+05:30

997 Views

Advertisements