Bash脚本计算平均分数



我有一个有很多标记的文件。脚本的目的是能够在屏幕上打印每个学生的平均分数。

Charles:1:8:9
Daniel:1:3:3
Josh:4:6:1
Alfonso:7:5:1
Eric:6:8:5

我尝试了以下代码:

cat /home/sysadmin/MARKS.txt | while read line
do
# These extracts the 3 marks of each student.
mark1=`cat /home/sysadmin/MARKS.txt | cut -d":" -f2`
mark2=`cat /home/sysadmin/MARKS.txt | cut -d":" -f3`
mark3=`car /home/sysadmin/MARKS.txt | cut -d":" -f4`
# Calculate average.
let add=$mark1+$mark2+$mark3
let avgMark=$add/3
# Print average.
echo $avgMark

但在屏幕上,script只在每个学生中返回0,如下所示:

0
0
0
0
0

如果有任何帮助,我们将不胜感激,提前感谢!!新年快乐!!

如果您可以使用awk(在循环中不需要使用太多命令(,您可以尝试以下操作,可以在单个awk中完成。

awk 'BEGIN{FS=":"} {print "Average for student "$1 " is: " ($2+$3+$4)/3}' Input_file

解释:添加以上详细解释。

awk '              ##Starting awk program from here.
BEGIN{             ##Starting BEGIN section of this program from here.
FS=":"           ##Setting FS as colon here.
}
{
print "Average for student "$1 " is: " ($2+$3+$4)/3
##printing student name(1st column) and printing avg(adding 2nd, 3rd and 4th column) and dividing it with 3 here.
}
' Input_file       ##Mentioning Input_file name here.

使用bash和数组($col(:

#!/bin/bash
declare -i av   #  set integer attribute
while IFS=":" read -r -a col; do
av=(${col[1]}+${col[2]}+${col[3]})/3
echo "${col[0]}: $av"
done < MARKS.txt

输出:

查尔斯:6丹尼尔:2Josh:3阿方索:4Eric:6

参见:help read

这是一个Perl:

$ perl -F: -lanE  '$sum=0; for $i (1 .. $#F) 
{$sum+=$F[$i]} 
printf "%s: %.2fn", $F[0], $sum/$#F;' file
Charles: 6.00
Daniel: 2.33
Josh: 3.67
Alfonso: 4.33
Eric: 6.33

或者,也许是一个更花哨的输出:

$ perl -F: -lanE  '$sum=0; for $i (1 .. $#F) 
{$sum+=$F[$i]} 
printf "%-10s%.2f average with %i scoresn", 
$F[0].":", $sum/$#F, $#F;' file

这也是您可以在awk:中使用的方法

$ awk -F: '{sum=0
for (i=2; i<=NF; i++) sum+=$i
printf "%-10s%.2f average with %i scoresn", 
($1 ":"), sum/(NF-1), NF-1}' file

这两个都打印:

Charles:  6.00 average with 3 scores
Daniel:   2.33 average with 3 scores
Josh:     3.67 average with 3 scores
Alfonso:  4.33 average with 3 scores
Eric:     6.33 average with 3 scores

相关内容

  • 没有找到相关文章

最新更新