<分区>
我知道如何在一行中求和,我可以使用awk。但是如果情况不同,我该怎么办?例如,
orange 2000
orange 1000
orange 1500
apple 900
apple 1100
peach 1500
peach 800
peach 1200
而且我想分别得到每个水果的总数。
<分区>
我知道如何在一行中求和,我可以使用awk。但是如果情况不同,我该怎么办?例如,
orange 2000
orange 1000
orange 1500
apple 900
apple 1100
peach 1500
peach 800
peach 1200
而且我想分别得到每个水果的总数。
最佳答案
您也可以使用 awk
,通过使用关联数组:
pax> echo 'orange 2000
orange 1000
orange 1500
apple 900
apple 1100
peach 1500
peach 800
peach 1200' | awk 'NF>=2{sum[$1]+=$2}END{for(i in sum){print i" "sum[i]}}'
orange 4500
apple 2000
peach 3500
详细看脚本:
NF >= 2 { # Want at least two fields
sum[$1] += $2 # For each line, add to sum for that key
}
END { # After all lines processed.
for (i in sum) { # Process each key in sum array
print i" "sum[i] # Output key and sum
}
}
关于linux - 如何在 linux shell 中进行求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43199118/