How to empty large files in Linux

Everything Linux, A.I, IT News, DataOps, Open Source and more delivered right to you.
Subscribe
"The best Linux newsletter on the web"

Hello, friends. In this post, you will learn How to empty large files on Linux. Of course, we will use the easiest and fastest method, which is with the terminal.

In the case of Linux, it is common to deal with configuration files or text files that are very large. These can be log files, or simple annotations that are generated with the use of the system.

These files can sometimes weigh as much as GB, so the question arises as to how to empty them. You might think at this point, that the best thing to do would be to delete them, but as I told you many times, especially in log files, it might not be convenient.

So, today we will show you some ways to do it.

How to empty large files on Linux

For this post, a file called sample.conf has been created, and I have filled it with a lot of content.

Use the du command to display the time of the file, so you can verify the changes.

du -sh sample.conf

Sample output

Showing file size
Showing file size

Now, with the file ready, let’s look at the methods.

Method 1: Using the command cat

The most common use of the cat command is to display the contents of a text file.

cat file.txt

This way, you can quickly access the contents without modifying it.

But you can also use this command to empty the contents of a text file.

To achieve this, just run

cat /dev/null > sample.conf

Now repeat the du command to display the change

du -sh sample.conf
Empty large files in Linux
Empty large files in Linux

As you can see, the whole thing went well.

Method 2: Redirecting to Null

Another simple method is to simply redirect to null. To achieve this, then, you can run.

> sample.conf

As you can see, this is a more condensed form of the command.

Again, commit the changes

du -sh sample.conf

Method 3: Using the echo command

The echo command is used to display an output on the screen, and from there you can redirect it. You can also use it to clean up the contents of a file.

To achieve this, you can use this command

echo "" > sample.conf

Although it is not the most effective method since there may be some memory leftovers, it does the job.

Conclusion

On Linux, we can do many things using the terminal because it is faster and more efficient. One of them is to empty a text file.

Everything Linux, A.I, IT News, DataOps, Open Source and more delivered right to you.
Subscribe
"The best Linux newsletter on the web"
Angelo
Angelo
I am Angelo. A systems engineer passionate about Linux and all open-source software. Although here I'm just another member of the family.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest articles

Join us on Facebook