我有一个可执行文件,说它被称为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
Run Code Online (Sandbox Code Playgroud)
我可以将输入存储在一个文件(input.txt)中并将其重定向到a.out,文件看起来像这样 -
0 0 10
10 10 5
Run Code Online (Sandbox Code Playgroud)
我可以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
Run Code Online (Sandbox Code Playgroud)
现在我想在该文件中存储多个输入并重定向到a.out.该文件看起来像2个输入 -
0 0 10
10 10 5
0 0 20
10 10 6
Run Code Online (Sandbox Code Playgroud)
我正在写一个像bash脚本
exec 5< input.txt
while read line1 <&5; do
read line2 <&5;
./a.out < `printf "$line1\n$line2"` ;
done
Run Code Online (Sandbox Code Playgroud)
它不起作用,我该怎么做?
<需要包含内容的文件名,而不是内容本身.您可能只想使用管道:
exec 5< input.txt
while read line1 <&5; do
read line2 <&5
printf "%s\n%s\n" "$line1" "$line2" | ./a.out
done
Run Code Online (Sandbox Code Playgroud)
或流程替代:
exec 5< input.txt
while read line1 <&5; do
read line2 <&5
./a.out < <(printf "%s\n%s\n" "$line1" "$line2")
done
Run Code Online (Sandbox Code Playgroud)
但是,您不需要使用单独的文件描述符.只需将标准输入重定向到循环:
while read line1; do
read line2
printf "%s\n%s\n" "$line1" "$line2" | ./a.out
done < input.txt
Run Code Online (Sandbox Code Playgroud)
您也可以使用here文档(但请注意缩进):
while read line1; do
read line2
./a.out <<EOF
$line1
$line2
EOF
done < input.txt
Run Code Online (Sandbox Code Playgroud)
或者这里的字符串:
while read line1; do
read line2
# ./a.out <<< $'$line1\n$line2\n'
./a.out <<<"$line1
$line2"
done < input.txt
Run Code Online (Sandbox Code Playgroud)
可以使用特殊$'...'引号来包含换行符,该引号可以指定换行符\n',或者字符串可以简单地具有嵌入换行符.
如果您使用bash4或更高版本,则可以使用该-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
Run Code Online (Sandbox Code Playgroud)