繁体   English   中英

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

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

我总是被咬 (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

不知道可以计算它的 bash 吗?

使用 awk:

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)
}

像这样运行上面的 awk 程序:

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

这里使用的逻辑是继续将数字除以 1024,直到原始数字小于 1024。并且在每次除法期间增加一个计数。 计数最终映射到单位以获得适当的单位。 函数 calc 被递归调用。

例如:I/p:1000bytes:在这种情况下,因为没有。 小于 1024,不进行除法,计数器为 0。计数器映射到字节索引。

I/p : 2050 : 除以 1024,计数加 1。除法后,由于没有。 小于 1024,则以计数器指向的单位打印,在本例中为 Kb。

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