如果(在zsh中)我有一个包含这样的数组:
echo ${fsizes[@]}
9.5M 100M 5G 15G 1.2T
有一种简单的方法可以在选择的输出中获得这些的总和(即字节,兆字节,千兆字节等?)
答案 0 :(得分:5)
#!/bin/zsh
fsizes=( 9.5M 100M 5G 15G 1.2T )
typeset -A unit
unit=( B 1 K 1024 M 1048576 G 1073741824 T 1099511627776 )
sumSize(){
sum=0
for sz; do
u=${sz//[^BKMGT]/}
n=${sz//$u/}
b=${unit[$u]}
(( sum += b * n ))
done
out="${@:(-1)}"
echo "Sum is $(( sum / ${unit[$out]} )) $out"
}
$ sumSize ${fsizes[@]} "B"
Sum is 1341003608883.2 B
$ sumSize ${fsizes[@]} "K"
Sum is 1309573836.8 K
$ sumSize ${fsizes[@]} "M"
Sum is 1278880.7 M
$ sumSize ${fsizes[@]} "G"
Sum is 1248.90693359375 G
$ sumSize ${fsizes[@]} "T"
Sum is 1.2196356773376464 T