user2312186
user2312186

Reputation: 473

doing math in two different file in linux

I have two data file each of them has 3 columns. How can I divided the corresponding elements in third columns in these two files and write it in another file in linux or awk.

Experiment Replica Mean
General0 0 408.5
General0 1 461.162
General0 2 428.23
General0 3 373.771
General0 4 396.243

Experiment Replica Mean
General0 0 124.674
General0 1 142.017
General0 2 145.206
General0 3 118.493
General0 4 126.985

Experiment Replica Mean
General0 0 124.674 / 408.5
General0 1 
General0 2 
General0 3 
General0 4 

Upvotes: 0

Views: 558

Answers (2)

iruvar
iruvar

Reputation: 23364

Assuming that corresponding records occur at identical positions in both files, the files can be pasted together

paste file1.txt file2.txt | 
awk '/Mean/{print($1, $2, $3)} ! /Mean/ {print($1, $2, $6/$3)}'

Experiment Replica Mean
General0 0 0.3052
General0 1 0.307955
General0 2 0.339084
General0 3 0.31702
General0 4 0.320473

Here's sudo_O's classy version of the above:

paste file1.txt file2.txt | awk '{print $1,$2,/Mean/?$3:$6/$3}'

Upvotes: 1

Chris Seymour
Chris Seymour

Reputation: 85785

awk 'FNR==NR{a[$1,$2]=$3;next}FNR==1{print;next}{print $1,$2,$3/a[$1,$2]}' f1 f2
Experiment Replica Mean
General0 0 0.3052
General0 1 0.307955
General0 2 0.339084
General0 3 0.31702
General0 4 0.320473

Tip: column -t is a nice tool for formatting your output into a table:

awk .... | column -t
Experiment  Replica  Mean
General0    0        0.3052
General0    1        0.307955
General0    2        0.339084
General0    3        0.31702
General0    4        0.320473

Explanation:

FNR==NR {            # FNR==NR is only true in the first file 
    a[$1,$2]=$3      # Build array, keys are field 1 and 2, value is field 3
    next             # Skip to the next line in the file
}
FNR==1 {             # If we are on the first line in the second file
    print            # Print the line
    next             # Go grab the next line
}
{
    x=$3/a[$1,$2]    # Do the math (the value of a[$1,$2] is $3 from file1)
    print $1,$2,x    # print the output
}

To run the script in this form save it to a file script.awk and do awk -f script.awk f1 f2.

Upvotes: 3

Related Questions