使用awk和printf进行for循环bash

时间:2014-07-26 13:06:18

标签: bash awk

如何在for循环中使用awk和printf?

这是我的代码

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

我收到以下错误

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

预期输出

  sample1  52432
  sample2  32909
  sample3  54000
  sample5  45890

由于

1 个答案:

答案 0 :(得分:1)

Awk永远无法扩展shell变量。您还试图仅将一个参数传递给printf(%d没有传递任何内容。

也许你想要这样:

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

请注意,使用双引号可以直接将变量的值嵌入到awk的代码中,但不建议这样做:

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

建议:

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

或者

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