arrays - Bash:数组变量在for循环中返回空输出
问题描述
我正在尝试开发一个嵌套的 for 循环,它将在 .txt 文件上运行带有两组整数的 awk 命令。循环应该执行以下操作:
- 对于等于或大于给定长度 i 和给定百分比 j 的行,打印第 2 列
- 计算唯一行数
- 输出计数到文件
我创建了这个:
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
解决方案
推荐阅读
- javascript - 如何在不返回浏览器的情况下使用 JavaScript 返回上一个路由?
- mysql - 如何将csv文件的某些列导入mysql phpmyadmin
- mongodb - MongoDB 的查询优化器有多可靠?
- c# - 在 C# 中替换 xml 字符串时出错
- php - 如何回显在 unlink 方法中的函数中返回的变量
- json - 将 JSON 转换为缺少字段名的 CSV
- c++ - 使用基于此标志的条件语句是否比添加更多代码行更有效?
- .net-core - .Net Core 查询来自不同微服务的记录
- javascript - 使用“relay-test-utils”测试反应组件
- swift - 你能在 Swift 中测试目标配置吗?