Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File size in human readable format

Tags:

linux

bash

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.

like image 844
someguy Avatar asked Apr 06 '13 18:04

someguy


People also ask

What is human readable size?

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.

What is a human readable file?

A human-readable medium or human-readable format is any encoding of data or information that can be naturally read by humans.

What command will output the size of files in your directory in human-readable format?

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.

How do you check GB file size?

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.


3 Answers

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.

like image 87
MelBurslan Avatar answered Oct 12 '22 16:10

MelBurslan


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.

like image 22
Evi1M4chine Avatar answered Oct 12 '22 15:10

Evi1M4chine


ls -lah /path/to/your/file | awk -F " " {'print $5'}
like image 13
David J Merritt Avatar answered Oct 12 '22 16:10

David J Merritt