简体   繁体   中英

Maths on multiple fields on seperate lines using awk

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?

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

result:

sum: 6557076.288

Note

  • 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

EDIT

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 'NR>1 {print $1-a} {a=$1}' inputfile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM