我有一个可执行文件,说它叫a.out
。提示后需要两行输入 -
> ./a.out
> give me input-1: 0 0 10
> give me input-2: 10 10 5
> this is the output: 20 20 20
我可以将输入存储在文件(input.txt)中并将其重定向到a.out
,文件看起来像这样 -
0 0 10
10 10 5
我可以像{ - 1}}一样打电话给
a.out
现在我想在该文件中存储多个输入并重定向到> ./a.out < input.txt
> give me input-1: 0 0 10 give me input-2: 10 10 5
> this is the output: 20 20 20
。该文件将显示为2个输入 -
a.out
我正在写一个像 -
这样的bash脚本0 0 10
10 10 5
0 0 20
10 10 6
它不起作用,我该怎么做?
答案 0 :(得分:5)
<
需要包含内容的文件名,而不是内容本身。您可能只想使用管道:
exec 5< input.txt
while read line1 <&5; do
read line2 <&5
printf "%s\n%s\n" "$line1" "$line2" | ./a.out
done
或流程替换:
exec 5< input.txt
while read line1 <&5; do
read line2 <&5
./a.out < <(printf "%s\n%s\n" "$line1" "$line2")
done
但是,您不需要使用单独的文件描述符。只需将标准输入重定向到循环:
while read line1; do
read line2
printf "%s\n%s\n" "$line1" "$line2" | ./a.out
done < input.txt
您也可以使用此处的文档(但请注意缩进):
while read line1; do
read line2
./a.out <<EOF
$line1
$line2
EOF
done < input.txt
或这里的字符串:
while read line1; do
read line2
# ./a.out <<< $'$line1\n$line2\n'
./a.out <<<"$line1
$line2"
done < input.txt
可以使用可以指定的特殊$'...'
引号来包含换行符
带\n'
的换行符,或字符串只能有一个嵌入的换行符。
如果您使用bash
4或更高版本,则可以使用-t
选项检测输入的结尾,以便a.out
可以直接从文件中读取。
# read -t 0 doesn't consume any input; it just exits successfully if there
# is input available.
while read -t 0; do
./a.out
done < input.txt