How can I shorten a file from the command line?
To truncate a file to 1 gigabyte, use the truncate
command:
truncate -s 1G file.xml
The result of truncation will likely not be a valid XML file but I gather that you understand that.
Documentation for the GNU version of truncate
is here and documentation for the BSD version is here
Assuming you want to truncate and extract the first 1 GB of the 150 GB file:
With head
:
head -c 1G infile > outfile
Note that the G
suffix can be replaced with GB
to align to 1000 instead of 1024.
Or with dd
:
dd if=infile of=outfile bs=1M count=1024
Or as in Wumpus Q. Wumbley's answer, dd
can truncate in place.
Where possible, I'd use the truncate
command as in John1024's answer. It's not a standard unix command, though, so you might some day find yourself unable to use it. In that case, dd
can do an in-place truncation too.
dd
's default behavior is to truncate the output file at the point where the copying ends, so you just give it a 0-length input file and tell it to start writing at the desired truncation point:
dd if=/dev/null of=filename bs=1048576 seek=1024
(This is not the same as the copy-and-truncate dd
in multithr3at3d's answer.)
Note that I used 1048576 and 1024 because 1048576*1024 is the desired size. I avoided bs=1m because this is a "portability" answer, and classic dd
only knows suffixes k
, b
, and w
.