[英]Using awk to calculate average of grades
I have a file like this: 我有一个像这样的文件:
id1 name1 grade1 grade2 grade3....gradeN
id2 name2 grade1 grade2 grade3....gradeN
etc
and I want to print the id, name and average of grades of each row using awk. 我想使用awk打印每行的id,名称和平均成绩。 any idea?
任何想法? the output should be like:
输出应该像这样:
id1 name1 avg_of_grades
id2 name2 avg_of_grades
Using awk
: 使用
awk
:
awk '{sum=0;for(i=3;i<=NF;i++) sum+=$i; print $1, $2, (NF>2?sum/(NF-2):0)}' file
Iterate from third column to end of line and capture the total in a variable called sum
. 从第三列迭代到行尾,并在名为
sum
的变量中捕获总数。 Once that is done, just print column 1, 2 and the average. 完成后,只需打印第1、2列和平均值。 Since
sum
will contain rolling total, we set it to 0
at the start of our script to initialize it for each line. 由于
sum
将包含滚动总计,因此我们在脚本开始时将其设置为0
,以针对每一行对其进行初始化。
Note for average, I used NF
variable which contains the total number of columns for each line. 注意,平均而言,我使用了
NF
变量,该变量包含每行的总列数。 We subtract 2 to get correct total (we start capture from third column). 我们减去2得到正确的总数(我们从第三列开始捕获)。
Also, I have added a check for division by zero in cases you just have two columns. 另外,如果您只有两列,我还会添加一个零除检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.