这是我的任务:逐行从文件中读取一些数据。对于每一行,如果满足某些条件,则要求用户输入内容并根据用户的输入继续。
我知道如何从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的方式?
答案 0 :(得分: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