首页 > 解决方案 > Bash:数组变量在for循环中返回空输出

问题描述

我正在尝试开发一个嵌套的 for 循环,它将在 .txt 文件上运行带有两组整数的 awk 命令。循环应该执行以下操作:

  1. 对于等于或大于给定长度 i 和给定百分比 j 的行,打印第 2 列
  2. 计算唯一行数
  3. 输出计数到文件

我创建了这个:

lens=(1000 2000 3000 5000)
percent=(80 90)
for i in ${lens[@]}
do
    for j in ${percent[@]}
    do
        echo "Length is $i and percent is $j"
        echo "Where length =>$i and % ID is >=$j, number of matches is: " >> output.txt
        awk '{if ($4>=$i && $3>=$j) print $2}' input.txt | uniq | wc -l >> output.txt
        awk '{if ($4>=1000 && $3>=80) print $2}' input.txt | uniq | wc -l >> output.txt
    done
done

出于某种原因,使用变量 i 和 j 会导致我的输出始终为 0,(即使它们不应该是) - 例如,第二个 awk 命令的输出返回正确的值,即使表面上这两行应该在循环的第一次迭代期间是等效的。查看输出文件的开头:

Where length =>1000 and % ID is >=80, number of matches is: 
0
775

感觉检查echo "Length is $i and percent is $j"打印正常输出:Length is 1000 and percent is 80. 第二个也是一样,echo "Where length>=$i..."所以我真的很难过。为什么数组变量的存在会导致 awk 出现问题?

编辑:嗯,像往常一样,答案非常简单,归结为几个''。正确的代码如下;注意 shell 变量 $i 和 $j 被 '' 包围:

for i in ${lens[@]}
do
    for j in ${percent[@]}
    do
        echo "Length is $i and percent is $j"
        echo "Where length =>$i and % ID is >=$j, number of matches is: " >> output.txt
        awk '{if ($4>=$'i' && $3>=$'j') print $2}' input.txt | uniq | wc -l >> output.txt
    done
done

标签: arraysbashfor-loop

解决方案


推荐阅读