2012-04-16 133 views
0

是否有可能走線槽的grep的結果,使用shell腳本像這樣使用grep?有什麼選擇?在while循環

謝謝!

+0

你想做什麼? grep從每行讀入的東西? – Brady 2012-04-16 10:10:33

回答

4

貌似你試圖使用process substitution

lines=5 
while read line ; do 
    let ++lines 
    echo "$lines $line" # Number each line 
    # Other operations on $line and $lines 
done < <(grep ...) 
echo "Total: $lines lines" 

提供grep實際上返回一些輸出線,其結果應該是這樣的:

6: foo 
7: bar 
Total: 7 lines 

這與grep ... | while ...略有不同:在前者中,grepsubshell中運行,而在拿鐵r while循環處於子外殼中。如果你想在循環中保持一些狀態,這通常只是相關的 - 在這種情況下,你應該使用第一種形式。

在另一方面,如果你寫

lines=5 
grep ... | while read line ; do 
    let ++lines 
    echo "$lines $line" # Number each line 
    # Other operations on $line and $lines 
done 
echo "Total: $lines lines" 

的結果將是:

6: foo 
7: bar 
Total: 5 lines 

哎喲!計數器被傳遞給子shell(管道的第二部分),但它不會返回到父shell。

+0

所以這可以用來單獨處理每一行,但我不能在循環中使用計數器?你能解釋一下這個語法嗎? – Xaero182 2012-04-16 15:03:25

3

grep是一個命令,但done < grep告訴shell使用名爲grep的文件作爲輸入。你需要的東西,如:

grep ... | while read line ; do 
    ... 
done 
+0

+1:D以秒爲單位打敗我 – 2012-04-16 10:10:06