简体   繁体   中英

read line by line from a file in shell scripting and display lowest 2 values

I have created a game in which user guesses the number that is randomly created by program and on successfully guessing program asks users name and stores the user name and score in a file. Now i want to print the name and score of 3 players who have lowest scores.

range=129
randNum=`expr $RANDOM % $range`     # generates a random number between 0 and 128

score=0

printf "Enter a number: "
read num

while [ $randNum -ne $num ];
do

    if [ $num -lt $randNum ]; then
        printf "Low guess"
        score=`expr $score + 1`
    else
        printf "High guess"
        score=`expr $score + 1`
    fi

    printf "\nEnter a number: "
    read num
done

read  -p "Enter your name: " name

FILE="gameScores.txt"
echo "$name     $score" >> $FILE

readFile=`cat $FILE`

# what should i do furthur to read from file sequentially and apply a condition for lowest scores

Try

sort -k 2,2n gameScores.txt | head -3

This will sort your score file based on the scores in the second field. You then just print out the first 3 scores, which should be your lowest scores.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM