关于用awk单独行多个字段数学 [英] Maths on multiple fields on seperate lines using awk

查看:112
本文介绍了关于用awk单独行多个字段数学的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在做一些数学上的3场×2行这样的文件:

I've been doing some maths on a 3 field x 2 line file like this:

3216.01   2724.81   1708.25
1762.48   617.436   1650.79

我的问题是我如何参照第一场的第一行,并在同样的计算,请参考第一场第二排?

My question is how do i refer to the first field on the first line and in the same calculation, refer to the first field in the second row?

和刚刚完成。我打算以$ 1(一号线)和minusing $ 1(2号线),那么平方和做同样为其它列,最后总结此值

And just for completion: I'm planning on taking $1 (line1) and minusing $1 (line2), then squaring and doing the same for the other columns and finally summing this value.

推荐答案

此行​​能与您的要求:

this line works with your requirement:

awk 'NR==1{for(i=1;i<=NF;i++)a[i]=$i}
NR==2{for(i=1;i<=NF;i++)s+=(a[i]-$i)^2; printf "sum: %.3f",s}' file

结果:

sum: 6557076.288

注意


  • 这应该与列数的动态工作,但究竟两行

  • 输出格式为%。3F ,如果你喜欢,你可以改变它

  • 的codeS可以缩短,因为有两个类似的对环结构

  • this should work with dynamic number of columns, but exactly two lines
  • the output format is %.3f, you could change it if you like
  • The codes could be shorten, since there are two similar for-loop structures

修改

由EdMorton的建议,上述codeS可以写成:

as suggested by EdMorton, the above codes could be written as:

awk 'NR==1{split($0,a)}
    NR==2{for(i=1;i<=NF;i++)s+=(a[i]-$i)^2; printf "sum: %.3f\n",s}' file

建议很好,我没有想到的分裂......感谢埃德!

very good suggestion, I didn't think of the split... thank Ed!

这篇关于关于用awk单独行多个字段数学的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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