0

How can I use awk and printf in for loop?

Here is my code

for fileName in /home/BamFiles/sample*
do
       sampleIds=${fileName##*/}

    for Bam in /home/BamFiles/sample*/*.bam
    do
        samtools idxstats $Bam | awk '{i+=$3+$4} END {printf("%s\t%d",$sampleIds Bam)}'
    done

 done

I get the the following error

 awk: fatal: not enough arguments to satisfy format string
 `%d    %s'
     ^ ran out for this one

Expected output is

  sample1  52432
  sample2  32909
  sample3  54000
  sample5  45890

Thanks

1 Answer 1

1

Awk can never be able to expand a shell variable. You are also trying to pass only a single argument to printf (nothing is passed for %d.

Perhaps you want it this way:

samtools idxstats "$Bam" | awk -v "file=$fileName" '{i+=$3+$4} END {printf("%s\t%d\n", file, i)}'

Note that embedding a variable's value directly to awk's code may be possible by using double-quotes but is not recommended:

samtools idxstats "$Bam" | awk "{i+=\$3+\$4} END {printf(\"%s\\t%d\", $file, i)}"

Suggestion:

shopt -s nullglob
for sample in /home/BamFiles/sample*; do
    for bam in "$sample"/*.bam; do
        samtools idxstats "$bam"
    done | awk -v sample="${sample##*/}" '{ i += $3 + $4 } END { printf("%s\t%d\n", sample, i) }'
done

Or

shopt -s nullglob
for sample in /home/BamFiles/sample*; do
    for bam in "$sample"/*.bam; do
        samtools idxstats "$bam" | \
            awk -v sample="${sample##*/}" -v bam="${bam##*/}" \
                '{ i += $3 + $4 } END { printf("%s\t%s\t%d\n", sample, bam, i) }'
    done
done
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for your answer. I was suppose to pass sampleIds to %d so I have edited it.
@hash Can you try my suggestions?
When you tried my first suggestion you probably omitted \ or added a space after it. I modified it to just run it as a line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.