求助:修改Bash脚本实现所有学生的成绩总分计算
修改Bash脚本计算多名学生成绩总分
成绩文件内容
Name: Rad Eng: 94 Tam: 98 Mat: 98 Soc: 98 Sci: 80 Name: Din Eng: 87 Tam: 89 Mat: 78 Soc: 87 Sci: 34 Name: Hardy Eng: 78 Tam: 87 Mat: 23 Soc: 34 Sci: 98
现有脚本
#!/bin/bash file=$1 num=$2 n=`wc -l < $file` it=$((n/num)) echo $n echo $it awk -v numm="$num" '{if (NR<=numm){T+=$2}}END{print T}' $file
问题分析
你的现有脚本存在两个核心问题:
- 错误地累加了
$2(这是学生的名字字符串,不是分数); - 逻辑只处理前
num行,但没有正确提取每个学生的各科分数进行求和。
下面提供几个针对性的解决方案,你可以根据实际需求选择:
方案1:计算所有学生的总分并输出(带名字)
这个脚本会遍历文件中每一行,提取学生名字和各科分数,计算总分后逐个输出:
#!/bin/bash file=$1 awk '{ # 提取学生名字(第2个字段) student_name = $2; # 累加各科分数:Eng($4)、Tam($6)、Mat($8)、Soc($10)、Sci($12) total_score = $4 + $6 + $8 + $10 + $12; printf "Student: %-6s Total Score: %d\n", student_name, total_score; }' "$file"
运行示例:
./your_script.sh scores.txt
输出结果:
Student: Rad Total Score: 468 Student: Din Total Score: 375 Student: Hardy Total Score: 320
方案2:根据参数指定计算单个学生的总分
如果你需要通过第二个参数指定计算第N个学生的总分(比如传入2计算Din的成绩),可以用这个版本:
#!/bin/bash file=$1 student_index=$2 awk -v idx="$student_index" 'NR == idx { total_score = $4 + $6 + $8 + $10 + $12; printf "Student %s (Line %d) Total Score: %d\n", $2, idx, total_score; }' "$file"
用法示例:
# 计算第2个学生的总分 ./your_script.sh scores.txt 2 # 计算第3个学生的总分 ./your_script.sh scores.txt 3
对应输出:
Student Din (Line 2) Total Score: 375 Student Hardy (Line 3) Total Score: 320
方案3:修正原脚本逻辑,计算前N个学生的总分总和
如果原脚本的意图是计算前num个学生的总分总和,修改后如下:
#!/bin/bash file=$1 num=$2 # 安全获取文件行数,避免空格问题 n=$(wc -l < "$file") it=$((n / num)) echo "Total lines in file: $n" echo "Lines per group: $it" awk -v numm="$num" 'NR <= numm { # 累加当前学生的各科分数到总和 total += $4 + $6 + $8 + $10 + $12; } END { print "Total score of first", numm, "students:", total; }' "$file"
运行示例:
./your_script.sh scores.txt 3
输出结果:
Total lines in file: 3 Lines per group: 1 Total score of first 3 students: 1163
内容的提问来源于stack exchange,提问作者Radhakrishnan Rk
相关产品推荐
相关产品推荐

