这是我的任务:逐行从文件中读取一些数据.对于每一行,如果它满足某些条件,则要求用户输入内容并根据用户的输入继续.
我知道如何从shell脚本逐行阅读内容:
while read line; do
echo $line
done < file.txt
Run Code Online (Sandbox Code Playgroud)
但是,如果我想做什么与用户交互的内部循环体.从概念上讲,这就是我想要的:
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
Run Code Online (Sandbox Code Playgroud)
我应该用另一种方式来读取文件吗?或者另一种读stdin的方法?
您可以在标准输入以外的文件描述符上打开文件.例如:
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
Run Code Online (Sandbox Code Playgroud)