sh script to sort, group and sum a flat file (146 Views)
Reply
Super Advisor
Ratzie
Posts: 846
Registered: ‎01-10-2002
Message 1 of 2 (146 Views)
Accepted Solution

sh script to sort, group and sum a flat file

I have the following flat file that is basically DATE #

Looks like this:

130426 246

130611 3

131011 28

131012 26
131131 117
131228 7

131231 117

 

 

I can sum up total, that is no problem.

But what I also what to do is group and sum by month.

So it will display:

1304 246

1306 3

1310 54

1312 124

 

Any help would be appreicated.

 

 

 

Please use plain text.
Acclaimed Contributor
Dennis Handly
Posts: 24,389
Registered: ‎03-06-2006
Message 2 of 2 (137 Views)

Re: sh script to sort, group and sum a flat file

[ Edited ]

I'm assuming the data is aready sorted.  If not, use "sort -k1.1,1.4" and pipe to this awk script.

Something like this:

awk '
BEGIN {
   sum = 0
   save_yymm = ""
}
{
yymm = substr($1, 1, 4)
if (yymm != save_yymm) {  # new month
   if (save_yymm != "")
      print save_yymm, sum
   save_yymm = yymm # save new
   sum = 0
}
sum += $2
}
END {
   print save_yymm, sum
}' input-file

Please use plain text.
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation