The truncated size depends on the original size of the file; the extra data will be lost if the file size is greater than the specified size.
Let’s start with different examples to see how we can truncate the file size.
Installing Coreutils Packages
The “truncate” command comes with most Linux distribution. It can also be installed, if not present, using the command given below:
Use the “grep” command to list the detail of packages:
How to Use the “truncate” Command?
The “>” shell redirection operator is the most popular and simplest way to truncate files.
Syntax
The syntax for truncating files with redirection is:
The “:” colon denotes true and has no output and the redirection operator “>” redirect the output to a specific file.
The file I am truncating is “test.sh”:
Another way to truncate file is:
It is removing the content of “test.sh” file.
Clear the Content of File
Use the “-s” option to remove the content of the files. This is a preferable way to manually delete a file. The truncate command effectively eliminates all the contents of a file. It does not delete the file itelf, but leaves it as a zero-byte file on the disk.
Let’s use truncate to clear file.txt to 0 bytes:
The file permissions and ownership will be preserved if you use the truncate command.
Use the “ls -lh” command to confirm the size:
Truncating a File to a Specific Size
To create a file, use:
To confirm the file permission and size of the file, use:
Let’s truncate the file to 100 bytes size:
To confirm the size, use:
To truncate a file size to 300K:
Type below mentioned command to check the size:
Extending the File Size
You can increase the file size by using the “+” with “-s” option. The file is currently 300k in size, as shown in the image below:
I’d like to increase the size of the file from 300k to 600k bytes:
The file size has been extended from 300k to 600k. Check the size:
Reducing the File Size
Let’s assume you have a 600k file and want to reduce its size to 270k, use “-s” option and “–” with the size figured:
The current size of the file is 330k.
Getting Help
To get a help message, use:
Checking Version
To check the version of the truncate command, use:
Conclusion:
Truncate is a very useful command for removing the content of a file while not deleting the file. You can also change the size of the file to the size you want it to be. We have learned how to truncate the content of a file, as well as how to shrink or extend the files in this article.
from Linux Hint https://ift.tt/3ykgN5n
0 Comments