Skip to content
Advertisement

File size in human readable format

Given the size of a file in bytes, I want to format it with IEC (binary) prefixes to 3 significant figures with trailing zeros, e.g. 1883954 becomes 1.80M.

Floating-point arithmetic isn’t supported in bash, so I used awk instead. The problem is I don’t how to keep the trailing zeros. Current solution:

if [ $size -ge 1048576 ]
then
    size=$(awk 'BEGIN {printf "%.3g",'$size'/1048576}')M
elif [ $size -ge 1024 ]
then
    size=$(awk 'BEGIN {printf "%.3g",'$size'/1024}')K
fi

(The files aren’t that big so I don’t have to consider bigger units.)

Edit: There’s another problem with this. See Adrian Frühwirth’s comment below.

Advertisement

Answer

GNU Coreutils contains an apparently rather unknown little tool called numfmt for numeric conversion, that does what you need:

$ numfmt --to=iec-i --suffix=B --format="%.3f" 4953205820
4.614GiB

I think that suits your needs well, and isn’t as large or hackish as the other answers.

If you want a more powerful solution, look at my other answer.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement