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.
You need to display the size of a file in kilobytes, megabytes, or gigabytes. Instead of displaying file sizes as 1,073,741,824 bytes, you want an approximate, human-readable size, such as 1 GB.
A human-readable medium or human-readable format is any encoding of data or information that can be naturally read by humans.
The du command displays the amount of file space used by the specified files or directories. If the specified path is a directory, du summarizes disk usage of each subdirectory in that directory.
Using the ls Command –l – displays a list of files and directories in long format and shows the sizes in bytes. –h – scales file sizes and directory sizes into KB, MB, GB, or TB when the file or directory size is larger than 1024 bytes. –s – displays a list of the files and directories and shows the sizes in blocks.
Is there any reason you are not using
ls -lh
command ? If you are on a Linux system which has been released in the last few years, you have this functionality.
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.
ls -lah /path/to/your/file | awk -F " " {'print $5'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With