Samanosuke Akechi
Samanosuke Akechi

Reputation: 361

AWK reading a file and operate between different columns

I have three files!

coord.xvg
veloc.xvg
force.xvg

each of these files have lines with multiple numbers lets say 10000 I would like to construct a script that

opens the three files reads columns and make arithmetic operations between them for every line.

For example

if every file has 4 words

coord.xvg >>  Time  x  y  z
veloc.xvg >>  Time vx vy vz
force.xvg >>  Time fx fy fz

and c,v,f stands for coord.xvg, veloc.xvg,force.xvg

if I write the operation 2*v*v+c*f*c the output should be
column1   Column2            Column3           Column4
Time      2*vx*vx+cx*fx*cx   2*vy*vy+cy*fy*cy  2*vz*vz+cz*fz*cz

I have found in the internet the following

awk '{
       { getline < "coord.xvg" ; if (FNR==90307) for(i=1;i<=2;i+=1) c=$i} 
       { getline < "veloc.xvg" ; if (FNR==90307) for(i=1;i<=2;i+=1) v=$i}
       { getline < "force.xvg" ; if (FNR==90307) for(i=1;i<=2;i+=1) f=$i}
     }
END {print c+v+f}' coord.xvg

which stands for my files which I want to begin reading after 90307 lines.

but it didn't help me much as it returns only the last values of every variable

Any thought??

Upvotes: 0

Views: 406

Answers (1)

Fredrik Pihl
Fredrik Pihl

Reputation: 45644

Something to get you started if I understood you correctly

$ cat *.xvg
Time 1 2 3
Time 4 5 6
Time 7 8 9
Time 10 11 12
Time 13 14 15
Time 16 17 18
Time 19 20 21
Time 22 23 24
Time 25 26 27

The following awk-script

{ if (FNR>=1) {
    { getline < "coord.xvg" ; c1=$2;c2=$3;c3=$4}
    { getline < "veloc.xvg" ; v1=$2;v2=$3;v3=$4}
    { getline < "force.xvg" ; f1=$2;f2=$3;f3=$4}
    print c1,c2,c3,v1,v2,v3,f1,f2,f3
    print $1, c1+v1+f1, c2+v2+f2, c3+v3+f3
}}

reads a line from each of the files and puts the data in variables as can be seen here

$ awk -f s.awk coord.xvg 
1 2 3 19 20 21 10 11 12
Time 30 33 36
4 5 6 22 23 24 13 14 15
Time 39 42 45
7 8 9 25 26 27 16 17 18
Time 48 51 54

The if (FNR>=1) part controls which lines are displayed. Counting starts at 1, change this to match your need. The actual calculations I leave to you :-)

Upvotes: 1

Related Questions