Bash命令来计算每一行和每一列的平均值 [英] Bash command to calculate average on each row and each column

查看:93
本文介绍了Bash命令来计算每一行和每一列的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个类似mark.log的日志文件,内容看起来像这样:

Suppose we have a log file like marks.log and the content looks something like this:

Fname   Lname   Net Algo    
Jack    Miller  15  20  
John    Compton 12  20  
Susan   Wilson  13  19  

我想添加一个包含每个人的平均值的新列,以及一个包含每个课程的平均值的新行.结果必须如下所示:

I want to add a new column that contains average for each person, and a new row that contains average for each course. The result has to look like this:

Fname   Lname   Net  Algo  Avg
Jack    Miller  15   20    17.5
John    Compton 12   20    16
Susan   Wilson  13   19    16
Average         13.3 19.6  -

推荐答案

如果您的数据位于 datafile.txt 中,则awk的语法可能类似于:

If your data is in datafile.txt, the syntax for awk could be something like:

awk '
  {
  # If it is the first row
  if (NR==1)
  print $0, "Avg";
  else
  # Print all fields, then the average of fields 3 & 4
  print $0,($3+$4)/2;
  # Get the total for field 3 and field 4
  t3+=$3; t4+=$4
  }
  # Once that is done...
  END {
  # Print the final line
  printf "Overall Average %.1f %.1f -\n",
  # The average of field 3 (NR is the Number of Records)
  t3/(NR-1),
  # The average of field 4 (NR is the Number of Records)
  t4/(NR-1);
  }' datafile.txt

这是带注释的长版.单线看起来像:

That's the long version with comments. The one-liner looks like:

awk '{if (NR==1) print $0, "Avg"; else print $0,($3+$4)/2; t3+=$3; t4+=$4}END{printf "Overall Average %.1f %.1f -\n",t3/(NR-1),t4/(NR-1);}' datafile.txt

这应该与所需的输出匹配.

This should match the desired output.

这篇关于Bash命令来计算每一行和每一列的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆