2012-04-16 140 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