for uniq entries add values in corresponding columns

Hi,

I have a file as listed below.. What I want to get is for each unique value in column 1 the corresponding values in the rest of the columns should be summed up..

 AAK1        0        1        0        11
AAK1        0        0        1        1
AAK1        0        0        1        2
AAK1        0        1        0        1
AAK1        0        0        1        1
AAK1        0        0        1        3
ABC1        0        1        0        13
ABC1        0        2        1        2
ABC1        0        0        1        4
ABC1        0        1        0        1
ABC1        0        2       1         1

AAK1 0 2 4 19
ABC1 0 5 3 20

Thanks,

AAK1 0 0 1 3

this script will summarize columns per first key column;

 
 
awk '{ key[$1]=$1; col1[$1]+=$2; col2[$1]+=$3; col3[$1]+=$4; col4[$1]+=$5; }
END{ for(x in key) print x, col1[x], col2[x], col3[x], col4[x]; }' input_file
1 Like

If all entries in your input file with the same key are adjacent (as they are in your problem statement), the following may be more efficient:

awk 'function printlast() {
	if (last != "") print last, sum2, sum3, sum4, sum5
}
	{if (last != $1) {
		printlast()
		last=$1
		sum2=$2
		sum3=$3
		sum4=$4
		sum5=$5
	} else {
		sum2+=$2
		sum3+=$3
		sum4+=$4
		sum5+=$5
	}
}
END	{printlast()}' input_file

especially if there are LOTS of different keys.