Shell脚本中不同列的平均值 [英] Average from different columns in shell script

查看:281
本文介绍了Shell脚本中不同列的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含10列的数据文件,如下所示

I have a datafile with 10 columns as given below

ifile.txt
2  4  4  2  1  2  2  4  2  1
3  3  1  5  3  3  4  5  3  3
4  3  3  2  2  1  2  3  4  2
5  3  1  3  1  2  4  5  6  8

我想添加第11列,该列将显示10列中每行的平均值.即AVE(2 4 4 2 1 2 2 4 2 1)等.尽管我的以下脚本运行良好,但是我想使其更简单,简短.预先感谢您在这方面提供的任何帮助或建议.

I want to add 11th column which will show the average of each rows along 10 columns. i.e. AVE(2 4 4 2 1 2 2 4 2 1) and so on. Though my following script is working well, but I would like to make it more simpler and short. I appreciate, in advance, for any kind help or suggestions in this regard.

awk '{for(i=1;i<=NF;i++){s+=$i;ss+=$i}m=s/NF;$(NF+1)=ss/NF;s=ss=0}1' ifile.txt

推荐答案

这应该有效

awk '{for(i=1;i<=NF;i++)x+=$i;$(NF+1)=x/NF;x=0}1' file

对于每个字段,您都将值添加到循环中的x.

For each field you add the value to x in the loop.

接下来,将字段11设置为x中的总和除以字段NF的数量.

Next you set field 11 to the sum in xdivided by the number of fields NF.

在下一行将x重置为零.

1等于true,并在awk中执行默认操作,即打印行.

1 equates to true and performs the default action in awk which is to print the line.

这篇关于Shell脚本中不同列的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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