Sometimes you may need to clear a large file or empty contents of a file in Linux without actually opening it. There are multiple ways to empty or delete contents of large file in Linux. In fact, it is a good way to regularly clear log files. But please be careful before executing these commands. There is no way to undo the results once you clear the contents of a file.
How to Empty or Delete Contents of Large File in Linux
Here are the steps to empty or delete contents of large file in Linux. For our example, we will empty the file located at /home/ubuntu/data.txt.
1. Clear File Content by Redirecting to Null
Here is the command to blank or empty a file by redirecting it to null.
# > /home/ubuntu/data.txt
After deletion, you can check its size using the following command.
# sudo du -sh /home/ubuntu/data.txt
Also read : How to Install Flask in Ubuntu
2. Empty File Using True or : command
Similarly, you can empty a file by redirecting true or equivalent (:) command to the file.
# true > /home/ubuntu/data.txt OR # : > /home/ubuntu/data.txt
Also read : How to Remove .php from URL in NGINX
3. Empty file using /dev/null
/dev/null is a file that has no content in it. It is typically used to redirect output of commands and scripts that you don’t want to display or save. It always remains empty.
So you can also redirect it to your large file to empty, as shown below.
# sudo cat /dev/null > /home/ubuntu/data.txt
You can also copy the contents of /dev/null to your file to delete its contents.
# sudo cp /dev/null > /home/ubuntu/data.txt
Also read : How to Convert List to String in Python
4. Delete File Content using Echo command
You can also clear file content by simply using echo with an empty string.
# sudo echo '' > /home/ubuntu/data.txt OR # sudo echo > /home/ubuntu/data.txt
Also read : How to Run Scripts on Startup in Ubuntu
5. Empty File Using Truncate Command
You can also blank the file using truncate command.
# sudo truncate -s 0 /home/ubuntu/data.txt
In this article, we have only shown some of the ways to clear the content of a file in Linux. There are many more ways to do it.
Also read : How to Install HAProxy in Ubuntu