Truncate Large Text File in UNIX / Linux

ht‮:spt‬//www.lautturi.com
Truncate Large Text File in UNIX / Linux

To truncate a large text file in UNIX or Linux, you can use the truncate command. This command allows you to resize a file to a specific size, either by truncating the file or by adding padding to the end of the file.

To truncate a file to a specific size, use the truncate command followed by the -s flag and the desired size. For example, to truncate a file named "large_file.txt" to 10 megabytes (MB), you would use the following command:

truncate -s 10M large_file.txt

This will resize the file to 10 MB, removing any content beyond that size.

You can also use the truncate command to add padding to the end of a file. To do this, use the -p flag followed by the desired size. For example, to add 10 MB of padding to the end of the file, you would use the following command:

truncate -s +10M -p large_file.txt

Note that the truncate command does not modify the original file. Instead, it creates a new file with the specified size and the same name as the original file. The original file is replaced with the new file, so you should use this command with caution.

If you want to preserve the original file, you can use the head command to extract the first N lines from the file, where N is the number of lines you want to keep. For example, to keep the first 10,000 lines of a file named "large_file.txt," you would use the following command:

head -n 10000 large_file.txt > small_file.txt

This will create a new file named "small_file.txt" with the first 10,000 lines of the original file. The original file will not be modified.

Created Time:2017-10-30 14:27:21  Author:lautturi