sum of column in text file using shell script

2019-06-14 16:12发布

I have file like this

1814 1
2076 2
2076 1
3958 1
2076 2
2498 3
2858 2
2858 1
1818 2
1814 1
2423 1
3588 12
2026 2
2076 1
1814 1
3576 1
2005 2
1814 1
2107 1
2810 1

I would like to generate report like this

1814 3
2076 6
3958 1
2858 3

Basically calculate the total for each unique value in column 1

标签: bash shell
4条回答
2楼-- · 2019-06-14 16:45

Using awk:

awk '{s[$1] += $2} END{ for (x in s) print x, s[x] }' input
查看更多
三岁会撩人
3楼-- · 2019-06-14 16:58

Pure Bash:

declare -a sum

while read key val ; do
  ((sum[key]+=val))
done < "$infile"

for key in ${!sum[@]}; do
  printf "%4d %4d\n" $key ${sum[$key]}
done

The output is sorted:

1814    4
1818    2
2005    2
2026    2
2076    6
2107    1
2423    1
2498    3
2810    1
2858    3
3576    1
3588   12
3958    1
查看更多
爷的心禁止访问
4楼-- · 2019-06-14 17:07

Perl solution:

perl -lane '$s{$F[0]} += $F[1] }{ print "$_ $s{$_}" for keys %s' INPUT

Note that the output is different from the one you gave.

查看更多
smile是对你的礼貌
5楼-- · 2019-06-14 17:08

sum totals for each primary key (integers only)

for key in $(cut -d\  -f1 test.txt | sort -u)
do
   echo $key $(echo $(grep $key test.txt | cut -d\  -f2 | tr \\n +)0 | bc)
done

simply sum a column of integers

echo $(cut -d\  -f2 test.txt | tr \\n +)0 | bc
查看更多
登录 后发表回答