当文件已重定向到stdin时,读取stdin以获取用户输入

Ara*_*ian 15 bash

所以我想尝试做以下事情:

while read line; do
    read userInput
    echo "$line $userInput"
done < file.txt
Run Code Online (Sandbox Code Playgroud)

所以说file.txt有:

Hello?
Goodbye!
Run Code Online (Sandbox Code Playgroud)

运行该程序将创建:

Hello?
James
Hello? James
Goodbye!
Farewell
Goodbye! Farewell
Run Code Online (Sandbox Code Playgroud)

问题(自然地)成为用户输入读取从stdin读取,在我们的例子中是文件.txt.有没有办法改变它从临时读取到终端的位置以获取用户输入?

注意:我正在使用的文件长度为200,000行.每条线长约500个字符.因此,如果需要,请记住这一点

jco*_*ado 24

您可以打开file.txt文件描述符(例如3)而不是使用重定向,并使用read -u 3从文件中读取而不是从stdin:

exec 3<file.txt
while read -u 3 line; do
    echo $line
    read userInput
    echo "$line $userInput"
done
Run Code Online (Sandbox Code Playgroud)

或者,正如Jaypal Singh所建议的那样,这可以写成:

while read line <&3; do
    echo $line
    read userInput
    echo "$line $userInput"
done 3<file.txt
Run Code Online (Sandbox Code Playgroud)

这个版本的优点是它也适用于sh(无法使用的-u选项).readsh