PUBLISHED ON: FEBRUARY 16, 2023
How to Shrink or Extend the Size of a File to the Specified Size (truncate Command)
In Linux, if we want to shrink or extend the size of a file, we use the truncate
command.
The truncate
command is used to shrink or extend the size of each FILE to the specified size in the Linux/Unix operating system. The meaning of trun-cat-ing is shortened by cutting off part.
- If we shrink a file that is larger than the specified size then extra data will be lost.
- If a FILE is shorter, it is extended and the sparse extended part (hole) reads as zero bytes.
- It is mandatory to use the option with the truncate command without any option with the truncate command we will get an error.
The general syntax of the truncate command.
truncate OPTION... FILE...
Brief description of options available with the truncate command.
Options |
Description |
-c, --no-create |
do not create any files |
-o, --io-blocks |
treat SIZE as the number of IO blocks instead of bytes |
-r, --reference=RFILE |
base SIZE on RFILE |
-s, --size=SIZE |
set or adjust the file size by SIZE bytes |
--help |
display this help and exit |
--version |
output version information and exit |
Example: Clear contents of a file using the truncate command.
In this example, we will clear the contents of a file with the help of the truncate command. It does not remove the file itself.
Example: Extend file size using the truncate command.
In the above example, we just shrink the file size of file actual size to 0 but in this example, we will extend the file size and set the size of the file 200k.
Example: Reduce the size of the file using the truncate command.
In the above example, we extend the file size 0 to 200k but in this example, we will reduce the file 200k to 100k. Using ls -lh <file name>
you can see the size of the file.
Example: Set the size of the file to another reference file using the -r option with the truncate command.
In this example, the size of textfile.txt is 100k and the new file size is 20k we will change the size of 20k to 100k.
Example: Display version information and exit.
Example: Display help and exit.
For more details about truncate command use truncate --help
this command display details about the truncate command with option and description.
Conclusion
In this tutorial, we covered how to shrink or extend the size of a file to the specified size in the Linux operating system using the truncate command with available options and suitable examples.