2

I wish to print $fname on each line of awk the ouput for the following:

for fname in $(ls *.bam | cut -c -9 | uniq)
    do
    echo $fname
    samtools depth  -a "$fname".bam | awk '{sum+=$3} END {print "Average = ", sum/NR}' >> mean.depth
    done

Current output:

$ less mean.depth  
    Average =  5.40089
    Average =  4.68387

Desired output:

$ less mean.depth  
    FILENAME1 Average =  5.40089
    FILENAME2 Average =  4.68387

So that the output mean depths are traceable. I've tried FILENAME and all sorts of things but not succeeding. Thanks!

GMK
  • 23
  • 4
  • 2
    since awk is acting upon stdin, FILENAME won't work... pass the shell variable containing filename, see https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script – Sundeep Nov 03 '17 at 08:50
  • Makes sense. Thank you! – GMK Nov 03 '17 at 09:40
  • 1
    @GMK: Since you found a solution, you should post it as an answer to your question – Thor Nov 03 '17 at 10:06

1 Answers1

0

SOLUTION

adapted from this answer

Define shell variable $fname with awk -v var=, then print it with END {print var

samtools depth  -a "$fname".bam | awk -v var=$fname '{sum+=$3} END {print var, " = ", sum/NR}' >> mean.depth
GMK
  • 23
  • 4