linux - 如何在 linux shell 中进行求和

标签 linux bash

<分区>

我知道如何在一行中求和,我可以使用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/

相关文章:

linux - openSuSE 远程备份方案

linux - 用于查找文本文件的 Unix 脚本不起作用

c - 在节头 elf 文件中获取 sh_name 成员

linux - 如何使用 Nginx 服务器在 Ubuntu 服务器上部署 dotnet 核心应用程序?

bash - 如何理解tee命令?

linux - 在串口 linux 上用交互式 bash 脚本替换登录提示

regex - 如何在 bash 脚本中匹配正则表达式中的数字

linux - 在目录中的文件内查找字符串然后复制它们

linux - 在 bash 脚本中调用别名命令

git - 有多少文件已更改?