[英]How can I read a file line by line and redirect each line to a variable in shell scripting?
[英]read line by line from a file in shell scripting and display lowest 2 values
我創建了一個游戲,用戶可以猜測程序隨機創建的數字,成功猜測程序會詢問用戶名並將用戶名和分數存儲在文件中。 現在,我想打印3個得分最低的球員的姓名和得分。
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
嘗試
sort -k 2,2n gameScores.txt | head -3
這將根據第二個字段中的分數對您的分數文件進行排序。 然后,您只需打印出前3個分數,這應該是您的最低分數。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.