如何在bash中读取文件和标准输入?

3
这里是我的任务:逐行从文件中读取数据。对于每一行,如果它满足某些条件,则要求用户输入一些内容,并根据用户的输入进行下一步操作。
我知道如何从 shell 脚本中逐行读取内容:
while read line; do
   echo $line
done < file.txt

然而,如果我想在循环体内与用户进行交互怎么办。概念上,这是我想要的:

while read line; do
    echo "Is this what you want: $line [Y]es/[n]o"
    # Here is the problem:
    # I want to read something from standard input here.
    # However, inside the loop body, the standard input is redirected to file.txt
    read INPUT
    if [[ $INPUT == "Y" ]]; then
       echo $line
    fi
done < file.txt

我应该使用其他方法来读取文件吗?还是使用另一种方法读取stdin?


可能是在read循环内读取stdin bash的重复问题 - Reinstate Monica Please
1个回答

9
您可以在文件描述符不是标准输入的情况下打开文件。例如:
while read -u 3 line; do     # read from fd 3
  read -p "Y or N: " INPUT   # read from standard input
  if [[ $INPUT == "Y" ]]; then
    echo $line
  fi
done 3< file.txt             # open file on fd 3 for input

可以用!谢谢! - monnand
@monnand 太好了!我已经在结尾添加了关闭 fd 3 的命令,并将打开的命令从输入/输出更改为只是输入。 - ooga
3
你也可以直接重定向循环的标准输入,而不是使用一对exec命令:while read -u 3 line; do ...; done 3< file.txt - chepner
@chepner 很棒的想法。已完成。 - ooga
1
done <3 file.txt is incorrect, it should be done 3< file.txt - David Šmíd
@DavidŠmíd 谢谢。 - ooga

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接