Count values based on condition
1
0
Entering edit mode
2.5 years ago

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 • 895 views
ADD COMMENT
1
Entering edit mode

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

ADD REPLY
1
Entering edit mode

What a great little tool datamash is, by the way.

ADD REPLY
1
Entering edit mode
2.5 years ago

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
ADD COMMENT

Login before adding your answer.

Traffic: 2781 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6