1

I have a file with many arrays, which has "identifiers" numbers in the first column. So I need to sum the numbers located in the second column based on that "identifiers" .

An example of the input:

1: 6.1703
44 10
46 18.3
44 45.9
46 3.9

2: 6.1932
44 11.2
46 4.3
44 15.6319
46 20.12

3: 16.5
45 22.8
45 18.3
46 31

the output need to be:

1: 6.1703
44 55.9
46 22.2

2: 6.1932
44 26.8319
46 24.42

3: 16.5
45 41.1
46 31
1
  • something akin to this or awk equivalent: perl -ane 'if($#F == 1){ $a{$F[0]} += $F[1] } else { while(($k,$v)=each %a){printf "%s %f\n", $k,$v};undef %a;print}' Jun 3, 2016 at 18:43

1 Answer 1

2

This will do the job

awk '
    /^[[:blank:]]*$/{for (k in a) print k, a[k]; delete a; print ""; next}
    /:/{print; next}
    {a[$1] += $2}
    END {for (k in a) print k, a[k]}
    ' data

1: 6.1703
44 55.9
46 22.2

2: 6.1932
44 26.8319
46 24.42

3: 16.5
45 41.1
46 31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .