Bash从文件嵌套循环读取线

时间:2016-02-19 18:33:35

标签: bash

我遇到了问题。基本上我有两个不同的文本文件,一个有问题,另一个有答案。循环从文件中读取第一个问题并等待用户输入,然后将输入与其他文本文件中的第一行进行比较。但它通过整个第二个文件并比较所有行。

有一个代码。

#!/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"

目前它做了什么,并从问题中获取第一行,与答案中的每一行进行比较,然后转到另一个问题。但我需要嵌套循环只与第一行比较并将一个问题移到另一个问题等等。

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分: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"