读取用户输入标准输入时,文件已经重定向到标准输入 [英] Read stdin for user input when a file is already redirected to stdin
问题描述
所以我试图做类似如下:
So I'm trying to do something like the following:
while read line; do
read userInput
echo "$line $userInput"
done < file.txt
所以说,file.txt的有:
So say file.txt has:
Hello?
Goodbye!
运行程序会创建:
Running the program would create:
Hello?
James
Hello? James
Goodbye!
Farewell
Goodbye! Farewell
问题(自然)变成了userinput从标准输入读取这对我们来说是file.txt的读取。有没有办法改变它的暂时从阅读到终端为了抢夺用户输入?
The issue (naturally) becomes that the userinput read reads from stdin which in our case is file.txt. Is there a way to change where it's reading from temporarily to the terminal in order to grab user input?
请注意:我一起工作的文件,20万行代码。每行约500个字符长。如果需要,所以记住这一点。
Note: The file I am working with is 200,000 lines long. and each line is about 500 chars long. So keep that in mind if needed
推荐答案
而不是使用重定向,可以打开 file.txt的
来文件描述符(例如3)并使用阅读-u 3
从文件而不是从读标准输入
:
Instead of using redirection, you can open file.txt
to a file descriptor (for example 3) and use read -u 3
to read from the file instead of from stdin
:
exec 3<file.txt
while read -u 3 line; do
echo $line
read userInput
echo "$line $userInput"
done
另外,通过Jaypal辛格的建议,这可以写为:
Alternatively, as suggested by Jaypal Singh, this can be written as:
while read line <&3; do
echo $line
read userInput
echo "$line $userInput"
done 3<file.txt
这个版本的优点是,它也适用于 SH
为<$ C(即 -u
选项$ C>读不工作 SH
)。
这篇关于读取用户输入标准输入时,文件已经重定向到标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!