[Solved] Counting specific characters within each field

Hello,

I have a file like following:
ALB_13554 1 1 1
ALB_13554 1 2 1
ALB_18544 2 0 2
ALB_18544 1 0 1

This is a sample of my file, my real file has 441845 number of fields. What I want to do is to calculate the number of 1 and 2 in each column using AWK, so, the output file looks like this:

3 1 #for the first column which has three 1 and one 2
1 1
3 1

The zeros should be ignored.

Thank you very much for your help in advance.

awk '{
  for (i=2;i<=NF;i++) {
    n[i,$i]++
  }
}

END {
  for (i=2;i<=NF;i++) {
    print n[i,1] " " n[i,2]
  }
}' file
1 Like

Perfect, thank you very much!

consider I have only "1" in the first field, this script gives me 4 but I want it to give me 0 too as the number of "2". So, to produce an output like this:

4 0

how I can put a condition in the previous script for that?

Thank you very much

With some assumptions (no field has a null/blank value):

awk '{
for(i=2;i<=NF;i++)
 if($i=="1") c_one++
  else if($i=="2") c_two++}
END{for(i=2;i<=NF;i++) printf("%d\t%d\n",c_one,c_two)}' file
1 Like

it worked perfectly, thanks a lot!