With Unix script, I'd like to add values in column 1 if text in column 2 is the same and print the sum. I have a file that is:
7 GeneA
2 GeneB
6 GeneC
2 GeneB
9 GeneA
I want the output to look like:
16 GeneA
4 GeneB
6 GeneC
Thanks
Use awk script:
awk '{ a[$2]+=$1 }END{ for(i in a) print a[i],i }' file
a[$2]+=$1
- accumulating values for each group("group" is considered as unique value of the 2nd field, used as array a
index)The output:
16 GeneA
4 GeneB
6 GeneC
Here is a solution using Perl:
perl -aE '$F{$F[1]}+=$F[0];END {say "$F{$_} $_" for keys %F}' file
With Google Crush Tools' subtotal
:
$ sort --key 2 yourFile.txt | subtotal --key 2 --sum 1 --delim ' '
7 GeneA
9 GeneA
16
2 GeneB
2 GeneB
4
6 GeneC
6