简体   繁体   English

BASH - 如何自动完成位、KB、MB、GB

[英]BASH - How to auto-completion bit, KB, MB, GB

I always result in bites (4521564 b)我总是被咬 (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?不知道可以计算它的 bash 吗?

Using awk:使用 awk:

f.awk contents: f.awk 内容:

$ 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 程序:

$ 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.这里使用的逻辑是继续将数字除以 1024,直到原始数字小于 1024。并且在每次除法期间增加一个计数。 The count is finally mapped to the units to get the appropriate unit.计数最终映射到单位以获得适当的单位。 The function calc is called recursively.函数 calc 被递归调用。

Eg: I/p: 1000bytes: In this case, since no.例如:I/p:1000bytes:在这种情况下,因为没有。 is less than 1024, no division is done and the counter is 0. The counter maps to bytes index.小于 1024,不进行除法,计数器为 0。计数器映射到字节索引。

I/p : 2050 : Divided by 1024 and count is incremented by 1. After division, since the no. I/p : 2050 : 除以 1024,计数加 1。除法后,由于没有。 is less than 1024, it is printed with the unit pointed by the counter, which in this case is Kb.小于 1024,则以计数器指向的单位打印,在本例中为 Kb。

shell doesn't do floating point without a helper so this shell function will round shell 不会在没有帮助程序的情况下执行浮点运算,因此此 shell 函数将舍入

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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