Bash-总和从阵列中一行值 [英] Bash- sum values from an array in one line
本文介绍了Bash-总和从阵列中一行值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的数组:
array=(1 2 3 4 4 3 4 3)
我可以得到数量最多的有:
I can get the largest number with:
echo "num: $(printf "%d\n" ${array[@]} | sort -nr | head -n 1)"
#outputs 4
但我想要得到的所有4的add总结起来,这意味着我希望它输出12(有3个出现4)代替。任何想法?
But i want to get all 4's add sum them up, meaning I want it to output 12 (there are 3 occurrences of 4) instead. any ideas?
推荐答案
用awk:
$ printf "%d\n" "${array[@]}" | sort -nr | awk 'NR>1 && p!=$0{print x;exit;}{x+=$0;p=$0;}'
12
使用排序,则数字以反向(-r)排序(-n)和AWK保持直到它找到一个号码是从previous 1不同的数字求和
Using sort, the numbers are sorted(-n) in reverse(-r) order, and the awk keeps summing the numbers till it finds a number which is different from the previous one.
这篇关于Bash-总和从阵列中一行值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文