ana_gg
ana_gg

Reputation: 370

Count the occurences of a number in all the columns in bash

I have a data set like this:

1 3 3 4 5 2 3 3
2 2 2 1 2 2 2 2 
1 3 3 3 3 3 3 3
1 4 4 4 4 4 4 3

I would like to count the number of times that the number "one" appears per column, so I would like the output like:

3 0 0 1 0 0 0 0

Does anyone know how to do it in bash?

Thank you very much! Ana

Upvotes: 0

Views: 115

Answers (1)

KamilCuk
KamilCuk

Reputation: 141165

Do it in awk. Iterate over number of fields and if the field is equal to 1 increment the array. Then on the end print the array.

awk '{ for (i = 1; i <= NF; ++i) { if($i == 1) { ++c[i]; } } 
  END{ for (i = 1; i <= NF; ++i) { printf "%d%s", c[i], i!=NF ? OFS : ORS; } }

Upvotes: 3

Related Questions