如何在linux shell中进行求和

时间:2017-04-04 05:43:07

标签: linux bash

我知道如何在一行中进行求和,我可以使用awk.But如果情况有所不同,我该怎么办?例如,

orange     2000
orange     1000
orange     1500
apple      900
apple      1100
peach      1500
peach      800
peach      1200

我想分别得到每种水果的总数。

3 个答案:

答案 0 :(得分:0)

您也可以使用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
    }
}

答案 1 :(得分:0)

另一种在bash中使用switch case的方法。即使水果不合适,这也会奏效。

#!/bin/bash

file=fruits.txt

while read -r line
do
        fruit=`echo $line | awk '{ print $1 }'`

        case "$fruit" in
                orange )
                value=`echo $line | awk '{ print $2 }'`
                val_or=`expr $val_or + $value`
                ;;

                apple )
                value=`echo $line | awk '{ print $2 }'`
                val_ap=`expr $val_ap + $value`
                ;;

                peach )
                value=`echo $line | awk '{ print $2 }'`
                val_pe=`expr $val_pe + $value`
                ;;
        esac
done < $file
        echo "orange: $val_or\napple: $val_ap\npeach: $val_pe\n"

答案 2 :(得分:0)

GNU datamash

datamash -W -g1 sum 2 < fruit 

输出:

orange  4500
apple   2000
peach   3500