Introduction
truncate is a command used to resize the file to the size you require. It helps you to delete the content inside a file without removing that file.
This command helps to truncate a file quickly and easily. The truncated file depends on the current file size; if the file size is larger than the specified size, the extra data will be lost.
This article will show you how to use the truncate command in Linux as we go through below.
Install Coreutils Packages
Run the apt command:
$ sudo apt install coreutils
Output:
Use the grep command to see the detail of packages:
$ dpkg -l | grep coreutils
Output:
The syntax of truncate command
$ truncate -s SIZE filename
The truncate command with examples
1. Clear the content of the file
Syntax:
$ truncate -s 0 filename
We will use du command to check the disk space used:
$ du -sh filename
Here the original size of skip.txt file is 4.0KB.
Now we will clear the content of skip.txt file following the syntax:
$ truncate -s 0 skip.txt
Then will use du command to check again:
$ du -sh skip.txt
Output:
Use the ls -lh command to check file size
$ ls -lh skip.txt
Output:
2. Truncate a file to the desired size
We will use du command to check the disk space used:
$ du -sh filename
Here the original size of hello.txt file is 4.0KB.
Now we will truncate the file to 400 bytes size:
$ truncate -s 400 hello.txt
Use the ls -lh command to check file size:
$ ls -lh hello.txt
Output:
3. Increase or decrease file size
You can use the prefix “+” or “-” with -s option to do this.
The dup.txt file is 400k:
Now we will try increasing 600k bytes:
$ truncate -s +600k dup.txt
Then check the file:
$ ls -lh dup.txt
Output:
Same as above, you can use the prefix “-” with -s option to decrease file size.
4. Get help
$ truncate --help
Output:
5. Check your version
$ truncate --version
Output:
Conclusion
You’ve already gone through the details of how to use the truncate command in Linux.
Thanks for reading.