(这间接地是更大的家庭作业的一部分)
我有类似的东西
在阅读 LINE 时 做 事情完成到$LINE echo "输入输入:" 读取输入 完成到 $INPUT 的事情 完成<infile
我找不到使用控制台/默认标准输入进行第二次读取的成功方法,而不是重定向的标准输入。
需要是纯伯恩脚本。
我相信这在 Bourne shell 中得到支持:
exec 3<doc.txt
while read LINE <&3
do
stuff-done-to-$LINE
# the next two lines could be replaced by: read -p "Enter input: " INPUT
echo "Enter input:"
read INPUT
stuff-done-to-$INPUT
done < infile
输入在文件和用户之间交替。事实上,这将是一种从文件中发出一系列提示的巧妙方法。
read
这会将文件“infile”重定向到第一个获取输入的文件描述符编号 3 。文件描述符 0 是stdin
, 1 是stdout
, 2 是stderr
。您可以与它们一起使用其他 FD。
我已经在 Bash 和 Dash 上对此进行了测试(在我的系统上,sh 符号链接到 dash)。
当然可以。这里有一些更有趣的:
exec 3<doc1.txt
exec 4<doc2.txt
while read line1 <&3 && read line2 <&4
do
echo "ONE: $line1"
echo "TWO: $line2"
line1=($line1) # convert to an array
line2=($line2)
echo "Colors: ${line1[0]} and ${line2[0]}"
done
这交替打印两个文件的内容,丢弃较长文件的多余行。
ONE: Red first line of doc1
TWO: Blue first line of doc2
Colors: Red and Blue
ONE: Green second line of doc1
TWO: Yellow second line of doc2
Colors: Green and Yellow
Doc1 只有两行。doc2 的第三行和后续行被丢弃。
您可以通过 /dev/tty 读/写用户的终端,这与您使用的 shell 以及是否重定向 stdin/stdout 无关,因此您只需要:
echo "Enter input:" > /dev/tty
read INPUT < /dev/tty
这应该工作:
for LINE in `cat infile`; do
stuff-done-to-$LINE
echo "Enter input:"
read INPUT
stuff-done-to-$INPUT
done
你不能。没有默认标准输入和重定向标准输入。有标准输入,它所连接的要么是控制台,要么是文件。
您唯一能做的就是在文件的行数上使用计数器。然后,使用 sed 或 tail+head 巧妙地提取每一行。您不能使用while read line
,因为您无法区分从控制台读取和从文件读取。