arrays - 从数组中的每个文件中读取行——条件永远不会成功
问题描述
我正在尝试将 cat 命令集成到 for 循环中,其中 cat 读取元素 '$currentccoutput' 但似乎(我认为) cat 是从字面上读取该行,而不是理解它是一个名为 a 的数组元素txt 文件。
#create an array of text files
currentccoutputs=($currentccfolder'/'*.txt*)
#basic for loop until I can get my cat command working
for currentccoutput in "${currentccoutputs[@]}"; do
cat "$currentccoutput" | while read LINE; do
# I have .txt files with three numbers per line
# that I would like to read / use
IFS=' ' read C1 C2 threshold
if [ $C1 != $C2 ] && [ $threshold \> 0.2 ]; then
echo "Huzzah!!!! Progress at last"
fi
done < "$currrentccoutput" # I don't know what
# this backwards chevron
# does but other people
# have used it...
done
我毫不怀疑这个片段还有其他不完美之处,但我对创建脚本是全新的,所以我试图将事情保持在我现在所知道的范围内,希望以后会出现复杂的解决方案。(现在,我正试图从 A 岛到 B 岛,那里的一些木头和一些麻绳既可以理解又可以复制。虽然我很欣赏关于 - 并希望有一天能建造 - 一艘像样的护卫舰的建议,现在它可能会让我有些困惑)。
我什至从来没有使用过'while''read'或'LINE',我已经从别人的解决方案中捏出来了。
我使用了 echo 命令来确保不是我的路径错误,只是我没有正确使用 cat。
解决方案
您使用方式的唯一问题是您使用cat
(更好的)shell-builtin 重定向来覆盖它。很好——事实上,它更可取;你不应该使用cat
,除非你绝对必须。[1]
问题是你在奔跑read LINE
,然后read C1 C2 threshold
彼此追逐,两者都来自同一个来源。
这意味着您将每个文件的第一行读入变量LINE
(您的代码再也不会查看),第二行读入变量C1
,C2
和threshold
. 如果有更多行,则将第三行读入LINE
,将第四行读入C1
//等C2
。threshold
如果您不想跳过所有其他行(从第一行开始),只需将其read LINE
全部取出,使您的代码类似于:
#!/usr/bin/env bash
case $BASH_VERSION in '') echo "ERROR: This script must be run with bash" >&2; exit 1;; esac
currentccoutputs=( "$currentccfolder"/*.txt )
for currentccoutput in "${currentccoutputs[@]}"; do
while IFS=$' \t\r' read -r c1 c2 threshold; do
if [ "$c1" != "$c2" ] && [ "$(bc -l <<<"$threshold > 0.2")" = 1 ]; then
echo "Huzzah!!!! Progress at last: c1=$c1; c2=$c2; threshold=$threshold"
fi
done < "$currentccoutput"
done
看:
- BashFAQ #1 -如何逐行(和/或逐字段)读取文件(数据流、变量)?
- BashFAQ #22 -如何使用浮点数而不是整数进行计算?(描述
bc
上面使用的成语) - BashFAQ #24 -我在管道中的循环中设置变量。为什么循环终止后它们会消失?或者,为什么我不能通过管道读取数据?(描述为什么
cat | while read
是一个坏主意)
[1] - 是的,这意味着您应该忽略很多(如果不是大多数)您在网上找到的 bash 代码示例。鲟鱼定律适用。
推荐阅读
- c++ - 脚本语言实现的高性能和优雅的类型调度
- python - 二叉树递归参数未更新
- r - 将 summarise() 输出转换为矩阵
- java - 在有向图中查找具有权重限制的两个顶点之间的所有路径
- r - selectInput 选择依赖于 R Shiny Flexdashboard 的另一个 selectInput
- python - 对所有 GUI 小部件应用一致的填充
- javascript - HighCharts/Javascript:将月度数据系列重新采样为季度/年度?
- javascript - JS - 如何将 cookie 更新到同一个站点 无
- scala - 如何使用 scala 的 List::groupBy 的结果?
- javascript - 如何模拟文件,用茉莉花隐藏?