0

I'd like to check if two rows start with the same number in the 1st column, if that happens, then the average of the 2nd column should be displayed. File example:

01  21    6    10%       93.3333%
01  22    50   83.3333%  93.3333%
02  20.5  23   18.1102%  96.8504%
02  21.5  100  78.7402%  96.8504%
03  22.2  0    0%        100%
03  21.2  29   100%      100%
04  22.5  1    5.55556%  100%
04  23.5  17   94.4444%  100%
05  22.7  9    7.82609%  100%
05  21.7  106  92.1739%  100%
06  23    11   17.4603%  96.8254%
06  22    50   79.3651%  96.8254%
07  20.5  14   18.6667%  96%
07  21.5  58   77.3333%  96%
08  21.8  4    100%      100%
09  22.6  0    0%        100%
09  21.6  22   100%      100%

For instance, the two first lines start with 01, but there is only one line starting with 08 (15th line). Therefore, the output based on these two cases should be:

01 21.5
...
...
...
08 21.8
...
...
...

I ended up with the following awk line, which works great when the file always has two similar lines, but it fails using the file shown above (because the 15th line):

awk '{sum+=$2} (NR%2)==0{print sum/2; sum=0;}'

Any hint is welcomed,

closed as off-topic by derobert, chaos, cuonglm, Scott, slm Sep 26 '15 at 2:13

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question has been posted on multiple sites. Cross-posting is strongly discouraged; see the help center and community FAQ for more information." – derobert, chaos, cuonglm, Scott, slm

  • So, am I understanding correctly that you want to average together all adjacent lines that have the same first column? (The average of one number is of course that number—so this includes spitting out rows without a pair unchanged). Also, does it have to be awk? – derobert Sep 25 '15 at 20:15
  • 2
    Also asked on stackoverflow.com/q/32789740/7552 -- there be answers there. @gery, one site at a time please. – glenn jackman Sep 25 '15 at 20:16
  • @glennjackman sorry for that Glenn, I will delete this one. – Gery Sep 25 '15 at 20:20
2

Maybe like this:

#!/usr/bin/awk -f
function reset(){
    n = $1; sum = $2; cnt = 1
}
{
    reset()
    while(getline){
        if(n == $1){
            sum += $2; cnt++;
        }else{
            print n, sum/cnt
            reset()
        }
    }
}
END{ print n, sum/cnt }

Not the answer you're looking for? Browse other questions tagged or ask your own question.