6

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

4 Answers 4

11

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
7

With GNU datamash command.

datamash groupby 2 sum 1 <infile.txt 
1
  • 2
    ++ , cause I like datamash Commented Sep 20, 2017 at 14:52
2

Here is a solution using Perl:

perl -aE '$F{$F[1]}+=$F[0];END {say "$F{$_} $_" for keys %F}' file 
1

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 

You must log in to answer this question.

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