2016-02-19 77 views
2

我被這個問題困住了。基本上我有兩個不同的文本文件,其中一個帶有問題,另一個帶有答案。 Loop從文件中讀取第一個問題並等待用戶輸入,然後將輸入與其他文本文件中的第一行進行比較。但它通過整個第二個文件並比較所有行。文件中的Bash嵌套循環readline

有一個代碼。

#!/bin/bash 

wrong=0 
right=0 

while IFS='' read -r question || [[ -n "$question" ]]; 
do 
echo "$question" 
read input </dev/tty 
while IFS='' read -r answer || [[ -n "$answer" ]]; 
do 
    if [[ $answer == *"$input"* ]] 
    then 
    ((right+=1)) 
    else 
    ((wrong+=1)) 
fi 
done < answers.txt 
done < file.txt 

echo "Wrong answers: $wrong" 
echo "Right answers: $right" 

它在看什麼,並採取從問題第一線,相比之下,在回答每一行,去了另一個問題。但我需要嵌套循環只與第一行比較,並移動到另一個問題等。

回答

3

既然你期待從tty輸入,我會假設文件不是非常大,記憶明智。因此,閱讀他們完全入內存似乎是可行的,並且巧妙的方法避免處理問題您有:

#!/bin/bash 

wrong=0 
right=0 

# Use mapfile to read the files into arrays, one element per line 
mapfile -t questions < questions.txt 
mapfile -t answers < answers.txt 

# Loop over the indices of the questions array 
for i in "${!questions[@]}"; do 
    question="${questions[i]}" 
    [[ $question ]] || continue 

    # Look up the answer with the same index as the question 
    answer="${answers[i]}" 

    # Use read -p to output the question as a prompt 
    read -p "$question " input 
    if [[ $answer = *"$input"* ]] 
    then 
     ((right++)) 
    else 
     ((wrong++)) 
    fi 
done 

echo "Wrong answers: $wrong" 
echo "Right answers: $right" 
+0

的事情是我需要看到一個問題,然後回答它,然後它會檢查來自answers.txt的答案,如果是正確的,然後遞增正確或如果我的答案是不正確的,那麼它會增加錯誤的變量。例如:Question1:........(在questions.txt中的第一行)然後我輸入「yes」或「no」,然後檢查我是否正確地轉到answers.txt的第一行 – Antoshjke

+0

@ Antoshjke更新。 – kojiro

+0

您的代碼有效,但它不會向我顯示問題。 – Antoshjke

0
Antoshije, 

You would need to break the loop . try the below 

#!/bin/bash 

let wrong=0 
let right=0 


function check_ans 
{ 
in_ans=$1 
cat answers.txt | while read ans 
do 
    if [[ "$in_ans" == "$ans" ]] 
     then 
     echo "correct" 
     break; 
    fi 
done 
} 

cat questions.txt | while read question 
do 
    echo $question 
    read ans 
    c_or_w=$(check_ans "$ans") 
    if [[ $c_or_w == "correct" ]] 
    then 
     right=$((right+1)) 
    else 
     wrong=$((wrong+1)) 
    fi  
done 
echo "Wrong answers: $wrong" 
echo "Right answers: $right"