一行中的数组中的 Bash-sum 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/13682408/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash- sum values from an array in one line
提问by teutara
I have this array:
我有这个数组:
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
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?
但是我想将所有 4 的加法相加,这意味着我希望它输出 12(4 次出现 3 次)。有任何想法吗?
回答by Mark Reed
dc <<<"$(printf '%d\n' "${array[@]}" | sort -n | uniq -c  | tail -n 1) * p"
- sortto get max value at end
- uniq -cto get only unique values, with a count of how many times they appear
- tailto get only the last line (with the max value and its count)
- dcto multiply the value by the count
- sort最后获得最大值
- uniq -c仅获取唯一值,并计算它们出现的次数
- tail只获取最后一行(带有最大值及其计数)
- dc将值乘以计数
I picked dcfor the multiplication step because it's RPN, so you don't have to split up the uniq -coutput and insert anything in the middle of it - just add stuff to the end.
我选择dc乘法步骤是因为它是 RPN,因此您不必拆分uniq -c输出并在其中插入任何内容 - 只需在最后添加内容即可。
回答by Guru
Using awk:
使用 awk:
$ printf "%d\n" "${array[@]}" | sort -nr | awk 'NR>1 && p!=awk -v RS=" " '{sum[echo $((${array// /+}))
]+=##代码##; if(##代码##>max) max=##代码##} END{print sum[max]}' <<<"${array[@]}"
{print x;exit;}{x+=##代码##;p=##代码##;}'
12
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.
使用排序,数字按倒序(-r)排序(-n),awk 不断对数字求和,直到找到一个与前一个不同的数字。
回答by Anders Johansson
You can do this with awk:
你可以这样做awk:
Setting RS(record separator) to space allows you to read your array entries as separate records.
将RS(记录分隔符)设置为空格允许您将数组条目作为单独的记录读取。
sum[$0]+=$0;means sumis a map of cumulative sums for each input value; if($0>max) max=$0calculates the max number seen so far; END{print sum[max]}prints the sum for the larges number seen at the end.
sum[$0]+=$0;手段sum是地图上的每个输入值累加和的; if($0>max) max=$0计算目前看到的最大数量;END{print sum[max]}打印最后看到的大数的总和。
<<<"${array[@]}"is a here-document that allows you to feed a string (in this case all elements of the array) as stdin into awk.
<<<"${array[@]}"是一个 here-document,它允许您将字符串(在本例中为数组的所有元素)作为 stdin 输入到awk.
This way there is no piping or looping involved - a single command does all the work.
这样就没有涉及管道或循环——一个单一的命令完成所有的工作。
回答by Gunnar
Using only bash:
仅使用 bash:
##代码##Replaceall spaces with plus, and evaluate using double-parenthesesexpression.

