
mgpg
Novice
Mar 12, 2008, 12:25 PM
Post #1 of 2
(1621 views)
|
|
Add successive entries
|
Can't Post
|
|
Hi, I have the following input: A,1 A,4 A,2 B,3 B,0 C,23 ... I want to simply output A, SUM(all A entries). I already sorted this file so all A's are successive. I can write simple perl script to do this as follows:
$prev; $sum = 0; $line =~ /(\w+),(\d+)/; $cur = $1; $n = $2; if ($cur == $prev) { $sum += $n;} else { print "$prev, $sum\n"; $sum = $n; } $prev = $cur; # loop This is probably not the most efficient but something like this will work I think. I wonder if I can write a one-liner from command line to do this. Thanks.
|