2011年6月15日 星期三

1-line awk group sum calculaton

0 意見
I got a data text file with these lines

2011-02-05  apple   3
2011-02-05  orange  5
2011-02-10  apple   4
2011-02-25  pineapple  2
2011-03-05  apple   1
2011-04-11  orange  2
2011-04-16  pineapple  3

and I want to get the grouped sum quickly, like this:

apple 8
orange 7
pineapple 5

and I really don't want to import into a spreadsheet and do the manual filtering jobs.

Here is the 1-line shell-script solution using 'awk'

$ cat file.txt | awk '{ sum[$2]+=$3 } END { for (i in sum) { print i,sum[i]}} ' | sort

It works like magic :)

0 意見:

張貼留言

 
My Unix Notes | © 2011 Design by DheTemplate.com and Theme 2 Blog

Find more free Blogger templates at DheTemplate.com - Daily Updates Free Blogger Templates