假设我用解析bash命令输出
find
(一些东西)| wc -l
然后我有输出像
14 file1.txt
29 file2.txt
32 file3.txt
1 tile4.txt
我完全陌生的bash脚本,但我希望发生我可以在命令写入另一个文件后马上使用这个输出。例如,如果计数大于10,我想在myotherfile.txt
中编写"ALERT! Count for file#.txt is greater than 10!"
。
感谢所有帮助
假设我用解析bash命令输出
find
(一些东西)| wc -l
然后我有输出像
14 file1.txt
29 file2.txt
32 file3.txt
1 tile4.txt
我完全陌生的bash脚本,但我希望发生我可以在命令写入另一个文件后马上使用这个输出。例如,如果计数大于10,我想在myotherfile.txt
中编写"ALERT! Count for file#.txt is greater than 10!"
。
感谢所有帮助
find ... -exec wc -l {} + |
while read count file
do
if [ $count -gt 10 ]
then echo "ALERT! Count for $file is $count" >>myotherfile.txt
fi
done
残留问题是在管道缓冲;有没有一种简单的方法来阻止这一点。 >> myotherfile.txt
的使用部分是为了解决这个问题。在一些方面,在整个循环上使用重定向会更简单(done > myotherfile.txt
,没有>>
重定向),但会有更多的缓冲。
请注意,您提出的管道:
find ... | wc -l
不会算在每个文件中的行;它只会计算find
命令生成的行数。
awk
可以做到这一点。
find [some stuff] | wc -l | awk '$1 > 10 {print "ALERT! Count for " $2 " is greater than 10!"}' > myotherfile.txt
请注意,每次运行该命令时,这将覆盖myotherfile.txt
。如果您希望将行添加到文件末尾,而不是每次运行它时,请使用>>
而不是>
。