我有一个带有很多标记的文件。该脚本的目标是能够在屏幕上打印每个学生的平均分数。
Charles:1:8:9
Daniel:1:3:3
Josh:4:6:1
Alfonso:7:5:1
Eric:6:8:5
Run Code Online (Sandbox Code Playgroud)
我试过下面的一段代码:
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
Run Code Online (Sandbox Code Playgroud)
但是在屏幕上,脚本只在每个学生中返回 0,如下所示:
0
0
0
0
0
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激,非常感谢提前!新年快乐!!
如果您awk没问题(我们不需要在循环中使用这么多命令),您可以尝试以下操作,可以单独完成awk。
awk 'BEGIN{FS=":"} {print "Average for student "$1 " is: " ($2+$3+$4)/3}' Input_file
Run Code Online (Sandbox Code Playgroud)
说明:为以上添加详细说明。
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.
Run Code Online (Sandbox Code Playgroud)