2014-09-22 69 views
3

我有一個可執行文件,說它叫a.out。這需要輸入的兩行的提示後 -如何將bash變量重定向到可執行文件?

> ./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 

,我可以打電話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 

現在我想以這種存儲文件多輸入重定向到a.out。該文件將看起來像這樣2個輸入 -

0 0 10 
10 10 5 
0 0 20 
10 10 6 

和我寫bash腳本一樣 -

exec 5< input.txt 
while read line1 <&5; do 
     read line2 <&5; 
     ./a.out < `printf "$line1\n$line2"` ; 
done 

它不工作,我該怎麼做呢?

+0

這可能有助於更具體地描述你的最終嘗試不能正確工作。 (如果沒有別的,從一般的高質量問題角度來看)。 – 2014-09-22 17:18:54

+0

使用'printf'%s \ n'「$ line1」「$ line2」''更安全。這樣,如果'line1'或'line2'中的任何內容讀取爲格式字符串,則不會引入錯誤。 – 2014-09-24 16:30:58

回答

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 
+1

'HERESTRING'也可以工作(不需要子shell)。 – 2014-09-22 17:18:26

+0

我剛剛添加了一個here字符串,但後來決定只添加一個here文檔,因爲在這裏字符串中嵌入換行符需要另一個新語法('$'... \ n ...'')或者看起來幾乎完全像這裏的doc一樣。 – chepner 2014-09-22 17:20:24

+1

+1爲'-t'選項 – user000001 2014-09-22 17:25:18

相關問題