Clear Contents of a File in Linux

Clear Contents of a File in Linux

When working with files in Linux, there might be required to clear the contents of a file without deleting file itself. One way to achieve that would be to open a file and clear contents. However, this method is inconvenient and requires much time.

Create a file for testing:

echo "Hello world" > test.txt

To clear contents of a file, we can use > redirection operator:

> test.txt

If need to clear contents of a file that requires sudo privileges, we can use truncate command with -s 0 option which sets the file size to zero:

sudo truncate -s 0 /var/log/kern.log

Leave a Comment

Cancel reply

Your email address will not be published.