2013-05-31 208 views
0

假設我用解析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!"

感謝所有幫助

回答

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命令生成的行數。

0

awk可以做到這一點。

find [some stuff] | wc -l | awk '$1 > 10 {print "ALERT! Count for " $2 " is greater than 10!"}' > myotherfile.txt 

請注意,每次運行該命令時,這將覆蓋myotherfile.txt。如果您希望將行添加到文件末尾,而不是每次運行它時,請使用>>而不是>