How can you trim files using the command line?

You can create a sparse file like this with dd:

dd of=file bs=1 seek=2G count=0
$ du file
0       disk
$ du --apparent-size file
2097152 disk

Generally speaking, just use dd; but as you mention the use of KVM virtualization, you might consider using qemu-img:

qemu-img create -f raw disk 2G

It does the same as the dd command in the answer of Chris Down, effectively.

Regardless of what command you use, for use in virtualization, I would strongly suggest using fallocate to pre-allocate blocks in order to prevent fragmentation and increase performance.

fallocate -l 2G disk

It's not available on all platforms and filesystems, though. This will not write zeroes, but just assigns blocks to the file, rather than doing that on-demand later every time it has to extend the file.


See also the GNU truncate command:

truncate -s 2G some-file