mirror of
https://github.com/moparisthebest/pacman
synced 2024-12-22 07:48:50 -05:00
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 <dreisner@archlinux.org>
This commit is contained in:
parent
ab8431c929
commit
a98fce0896
@ -28,7 +28,8 @@ EXTRA_DIST = \
|
||||
LIBRARY = \
|
||||
library/output_format.sh \
|
||||
library/parseopts.sh \
|
||||
library/human_to_size.sh
|
||||
library/human_to_size.sh \
|
||||
library/size_to_human.sh
|
||||
|
||||
# Files that should be removed, but which Automake does not know.
|
||||
MOSTLYCLEANFILES = $(bin_SCRIPTS)
|
||||
|
@ -35,3 +35,7 @@ successful, the converted byte value is written to stdout and the function
|
||||
returns 0. If an error occurs, nothing in written and the function returns 1.
|
||||
Results may be inaccurate when using a broken implementation of awk, such
|
||||
as mawk or busybox awk.
|
||||
|
||||
size_to_human.sh:
|
||||
The reverse of human_to_size, this function takes an integer byte size and
|
||||
prints its in human readable format, with SI prefixes (e.g. MiB, TiB).
|
||||
|
20
scripts/library/size_to_human.sh
Normal file
20
scripts/library/size_to_human.sh
Normal file
@ -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])
|
||||
}'
|
||||
}
|
Loading…
Reference in New Issue
Block a user