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:

JavaScript

(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:

JavaScript

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