假设我使用
find
(有些东西)| wc -l
然后我输出像
14 file1.txt
29 file2.txt
32 file3.txt
1 tile4.txt
我对Bash脚本完全不熟悉,但我想要发生的是我可以在命令后立即使用此输出写入另一个文件。例如,如果计数大于10,我想在"ALERT! Count for file#.txt is greater than 10!"
中写myotherfile.txt
。
感谢您的帮助
答案 0 :(得分:2)
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
命令生成的行数。
答案 1 :(得分:0)
awk
可以解决问题。
find [some stuff] | wc -l | awk '$1 > 10 {print "ALERT! Count for " $2 " is greater than 10!"}' > myotherfile.txt
请注意,每次运行命令时都会覆盖myotherfile.txt
。如果您希望每次运行时都将行添加到文件末尾,请使用>>
代替>
。