如何在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
由于
答案 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