shell 中循环的文件重定向

File redirection for loops in the shell

我试图了解循环的文件重定向如何在 shell 中工作,所以我编写了以下代码:

#!/bin/sh
while IFS='' read -r line; do
  echo 'reading '$line
  awk -F, '{sub(/.*/,"Completed",);print}'
done<

我为脚本提供了以下输入文件:

hello,hi,how are you
i,am,good

运行 上述文件的脚本输出为:

reading hello,hi,how are you
i Completed good

我期待以下形式的输出:

reading hello,hi,how are you
hello,Completed,how are you
i Completed good
reading i,am,good
hello,Completed,how are you
i Completed good

为什么循环不为两行打印 "reading"?而且,为什么第一行没有用 awk 替换?谁能解释一下脚本的输出?

您在循环中重定向的只有一个 stdinreadawk 都将从 stdin 读取。虽然 read 只消耗了一行(第一行),但 awk 愉快地消耗了其余部分。

在下一次迭代中,read没有更多内容可读,循环终止。

如果您想在 awk 的标准输入中提供数据,您必须明确地这样做,例如通过管道进入 awkprintf '%s\n' "$line" | awk ....