2016-02-19 53 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"