Search code examples
linuxbashfor-loopawksamtools

Print for loop input filename on piped awk output


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!


Solution

  • 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