在while循环中使用grep

Jon*_*ny5 2 shell grep

是否有可能通过使用这样的 shell 脚本来处理 grep 的结果:

while read line ; do
    ...
done < grep ...
Run Code Online (Sandbox Code Playgroud)

谁能解释为什么这不起作用?有哪些替代方案?

谢谢!

l0b*_*0b0 5

看起来您正在尝试使用进程替换

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"
Run Code Online (Sandbox Code Playgroud)

如果grep实际返回一些输出行,结果应如下所示:

6: foo
7: bar
Total: 7 lines
Run Code Online (Sandbox Code Playgroud)

这与grep ... | while ...: 在前者中,grepsubshel​​l 中运行,而在后者中,while循环在 subshel​​l 中略有不同。这通常仅在您想在循环内保留某些状态时才相关 - 在这种情况下,您应该使用第一种形式。

另一方面,如果你写

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"
Run Code Online (Sandbox Code Playgroud)

结果将是:

6: foo
7: bar
Total: 5 lines
Run Code Online (Sandbox Code Playgroud)

哎哟! 计数器被传递到子外壳(管道的第二部分),但它不会返回到父外壳。