From a98fce08968febe7395b30f15f070f400da089ed Mon Sep 17 00:00:00 2001 From: Dave Reisner Date: Sun, 6 May 2012 18:27:43 -0400 Subject: scripts/library: add size_to_human This function is the reverse of human_to_size, and converts integer byte sizes to human readable SI prefixed values. A logical extension of this might be to mimic the formatter that pacman uses and allow a second argument to be passed in which can coerce the size, rather than reducing until the unit count is below 1024. Signed-off-by: Dave Reisner --- scripts/library/size_to_human.sh | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 scripts/library/size_to_human.sh (limited to 'scripts/library/size_to_human.sh') diff --git a/scripts/library/size_to_human.sh b/scripts/library/size_to_human.sh new file mode 100644 index 00000000..9c0f0de2 --- /dev/null +++ b/scripts/library/size_to_human.sh @@ -0,0 +1,20 @@ +size_to_human() { + awk -v size="$1" ' + BEGIN { + suffix[1] = "B" + suffix[2] = "KiB" + suffix[3] = "MiB" + suffix[4] = "GiB" + suffix[5] = "TiB" + count = 1 + + while (size > 1024) { + size /= 1024 + count++ + } + + sizestr = sprintf("%.2f", size) + sub(/\.?0+$/, "", sizestr) + printf("%s %s", sizestr, suffix[count]) + }' +} -- cgit v1.2.3-24-g4f1b