简体   繁体   中英

BASH - How to auto-completion bit, KB, MB, GB

I always result in bites (4521564 b)

if the result is > 1 YB - print result in YB
if the result is > 1 ZB and < 1 YB - print result in ZB
if the result is > 1 EB and < 1 ZB - print result in EB
if the result is > 1 PB and < 1 EB - print result in PB
if the result is > 1 TB and < 1 PB - print result in TB
if the result is > 1 GB and < 1 TB - print result in GB
if the result is > 1 MB and < 1 GB - print result in MB
if the result is > 1 KB and < 1 MB - print result in KB

Do not know about the bash for which it can be calculated?

Using awk:

f.awk contents:

$ cat f.awk
function calc(num,i)
{
        if (num>=1024)
            calc(num/1024,i+1);
        else
           printf "%.2f %s\n", num,a[i+1];
}

BEGIN{
        split("b KB MB GB TB PB EB ZB YB",a);
        calc(val,0)
}

Run the above awk program like this:

$ awk -v val=4521564  -f f.awk
4.31 MB

The logic used here is to keep diving the number by 1024 till the original number becomes less than 1024. And during every division increment a count. The count is finally mapped to the units to get the appropriate unit. The function calc is called recursively.

Eg: I/p: 1000bytes: In this case, since no. is less than 1024, no division is done and the counter is 0. The counter maps to bytes index.

I/p : 2050 : Divided by 1024 and count is incremented by 1. After division, since the no. is less than 1024, it is printed with the unit pointed by the counter, which in this case is Kb.

shell doesn't do floating point without a helper so this shell function will round

byteme(){
v=$1
i=0
s=" KMGTPEZY"
while [ $v -gt 1024 ]; do
    i=$((i+1))
    v=$((v/1024))
done
echo $v${s:$i:1}b
}

byteme 1234567890
1Gb

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM