(Full discolosure that this is my first time working with sequence data, and with the bash scripting.)
I need to calculate the average coverage for any .bam file.
After some searching I wrote the following script:
# Script to calculate the average coverage of a genome sample
# compute the total length of the sample
tot=$(samtools view -H $1 | grep -P '^@SQ' | cut -f 3 -d ':' | awk '{sum+=$1} END {print sum}')
echo $tot
#compute the coverage at each point
samtools depth -ao cov_$1 $1 #your .bam file has depth calculated for each point
#calculate the average coverage
sum=$(awk '{sum+=$3} END {print sum}' cov_$1)
echo $sum
echo
avg=$(echo "$sum/$tot" | bc -l)
echo ''The average coverage of the sample $1 is $avg x.''
The logic behind the calculation of tot is as follows:
samtools view -H
gets the header of the bam file
grep -P
gets all lines in this header with SQ
cut -f 3 -d ':'
removes fields that are lists of more than 3 letters while -d uses delimiter ':' instead of tab and this leaves only the numbers i.e. lengths of the chromosomes
awk '{sum+=$1} END {tot=sum}'
calculates the length/total bases in the chromosome
However, my output seems incorrect. Any advice on where I might be making an error (in code or thought process), or a better method would be appreciated.
One thing that worries me is that my tot variable is the total number of bases, so if the samtools depth function does not calculate coverage for each base then my sum and tot will not be in the same units and my calculated coverage will be wrong...