Truncate empy space from a raw dd image

Justin asked:

I have a raw disk image I took using dd of a Ubuntu instance. The total disk size is 300 GB, but only 5.5 GB used.

Is there a way to resize the raw dd image down to 20 GB, keeping all of the 5.5 GB of data, and just truncating empty blocks?

My answer:

Just use virt-sparsify.

In its normal use, it writes a temporary file and then rewrites the original, with holes.

If you’re short on disk space, it can even reduce the file in-place, without writing a temporary copy, with the -i option, though this may not free up all possible space.

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.