This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Count values based on condition

Hi everyone,

I have a text file that looks like this

A 30
A 25
B 40
B 50
C 5
D 2

...

My goal is to count and sum all values on column 2, according to the condition in column 1. For example, A=55, B=90, C=5, D=2, etc. I've try using grep and wc, but I'm missing something here:

grep -o 'A\|B\|C\|D\' file | awk '{print $2}' | wc

Can you please help me out? Thanks!

sequence

how is it related to bioinformatics ?? (btw you want datamash groupby 1 sum 2 )

1 answer

Lets pretend this is a bioinformatics question.

$ cat bases.txt
A 30
A 25
C 40
C 50
G 5
T 2

Here is a simple perl solution:

$ perl -lane '$d{ $F[0] } += $F[1]; END {
 foreach (sort keys %d) { print "$_=$d{$_}" }
}' bases.txt
A=55
C=90
G=5
T=2

Log in to answer this question.