#! /bin/bash --posix
# requirements: vim-common
# sudo dnf -y install vim-common
function b_to_mb {
# get BASE conversion type
if [ "$3" = "BASE10" ]; then
# set for BASE10
BASE_DIV=1000000
else
if [ "$3" = "MIXED" ]; then
# set for MIXED
BASE_DIV=1024000
else
# set default for BASE2
BASE_DIV=1048576
fi
fi
# create array from string
# use bc with 6 digit precision to calculate megabytes from bytes
ARRAY=($1) && printf "scale=6; ${ARRAY[0]}/$BASE_DIV\n" | bc -l
}
# execute b_to_mb
b_to_mb $1 $2
gmk_fmt () { # bytes
# Apply a suffix to any byte value greater than 999. Returns a string w/len at most 6
# (f5.1 + modifier) with the appropriate modifier, K, M, G, T, P, E.
# Example: gb_fmt 370220929180 returns 344.7G
b=$1
d=0
s="EPTGMK "
while [ $b -ge 1000 ] ; do
d=$(((($((($b & 1023)))*100/1024)+5)/10)) # remainder mod 1024, rnd to nearest tenth
b=$(( ($b ) >> 10 )) # divide by 1024
s=${s:: -1} # advance the prefix
done
[ $d -ge 10 ] && { let b++ ; d=0; } # if rem is ".10," then bump the top unit
[ $d -gt 0 ] && suf=".$d" # apply decimal only if not a zero
echo ${b}${suf}${s: -1}
}
8条答案
按热度按时间vpfxa7rd1#
你可以用shell内置的
下面是一个更有用的版本:
7qhs6swi2#
这条线怎么样:
5jvtdoz23#
尝试使用bash内置函数(显示一个整数,就像KB版本一样)
uubf1zoe4#
xj3cbfub5#
使用
bc
和printf
bc
和printf
可用于显示具有可配置小数位数的输出,也可对数字进行分组:使用
numfmt
使用
numfmt
自动缩放输出单位:要使用
numfmt
输出到固定单元,例如M
:请参阅其手册页并确保正确使用。
nr9pn0ug6#
尝试使用
awk
$1
-第一列的值,本例中为大小(KB)fzwojiic7#
Github:index0-b-to-mb.sh
index0-b-to-mb.sh
https://en.wikipedia.org/wiki/Megabyte#Definitions
./index0-b-to-mb.sh '120928312 http://blah.com' MIXED
./index0-b-to-mb.sh '120928312 http://blah.com' BASE10
./index0-b-to-mb.sh '120928312 http://blah.com' BASE2
./index0-b-to-mb.sh '120928312 http://blah.com'
./index0-b-to-mb.sh "$(your_command)"
wtlkbnrh8#
下面是我编写的一个小例程,它只依赖于bash,并将任何大于1000的十进制字节值格式化为以K为单位的估计值(1024)、M(1024K),G(1024 M),T,Peta,Exa。它四舍五入到最近的十分位。最初的目的是将输出限制为固定的位数6,模拟
pv
命令的输出。仅用于估计目的,例如KB/秒传输速率。这里有一些测试代码来驱动它。正如所写的那样,它将生成随机值和转换。将“false”更改为“true”进行增量测试以验证舍入: