I have a bunch of genotype files genotype-HA1_1, ..., genotype-HA1_27. Rows are SNPs and columns are individuals.Number of individuals (i.e., columns) differs in each genotype file.Here are 2 examples of how they look like:

head genotype-HA1_1    
A   A   A   A   A   A   A   A   A   A
C   C   C   C   C   C   C   N   C   C
N   K   K   K   T   K   K   N   G   N
N   A   A   A   R   A   A   A   A   A
Y   Y   T   Y   C   T   Y   T   T   Y


head genotype-HA1_11
A   A   W   A   A   W   A   A   A   N   A
C   C   C   C   C   C   C   N   C   C   C
G   G   K   G   N   K   K   N   G   G   G
A   A   A   A   N   A   A   N   A   A   A

I want to count the total number of character "N" for each SNP and divide it to the number of individuals (i.e., columns) in each file over a loop.

my desired output


I am using something like this

for cfile in genotype-HA1_*; do
awk -F\N '{print NF-1/NF}' "$cfile" > count-"${cfile##*.}"; done

part of the code that counts the number of "N" works perfectly fine, I just do not know how to divid it into the number of columns in each file.

1 Answer 1


Instead of using N as a field separator, why not use the default whitespaces separator such that NF has its conventional interpretation (i.e. the number of columns), and use the return value of gsub to count the Ns?

$ awk '{print gsub("N","N")/NF}' genotype-HA1_1 

NOTE: gsub("N","N") counts occurrences of the character N in the record (line), which isn't generally the same as the number of fields that equal N (although in your sample input these are the same). If you need the stricter definition, then a KISS approach would be something like:

awk '{c = 0; for(i=1;i<=NF;i++) c += ($i == "N"); print c/NF}' genotype-HA1_1

You must log in to answer this question.

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