jeudi 1 août 2019

Awk if else expression not printing correct results for mathematical operation

So I have an input file that looks like this:

atom    Comp
C1  45.7006
H40 30.0407
N41 148.389
S44 502.263
F45 365.162

I also have some variables that I have called in from another file, which I know are defined correctly, as the correct values print when I call them using echo.

These values are

Hslope=-1.1120
Hint=32.4057
Cslope=-1.0822
Cint=196.4234

What I am trying to do is to for all lines with C in the first column, print (column 2 - Cint)/Cslope. The same for all lines with H in the first column with the appropriate variables and have all lines that don't have C or H print "NA".

The first line should be skipped.

Currently, my code reads

awk -v Hslope=$Hslope -v Hint=$Hint -v Cslope=$Cslope -v Cint=$Cint '{for(i=2; i<=NR; i++) 
{
    if($1 ~ /C/) 
    { shift = (($2-Cint)/Cslope); print shift } 
    else if($1 ~ /H/) 
    { shift = (($2-Hint)/Hslope); print shift } 
    else 
   { print "NA" }
} }' avRNMR >> vgRNMR 

Where avRNMR is the input file and vgRNMR is the output file, which is already created with the contents "shift" by another line.

I have also tried a version where print is just set to the mathematical expression instead using "shift" as a variable. Another attempt was putting $ in front of every variable. Neither of these have produced any different results.

The output I get is

shift
139.274
2.1268
2.1268
NA
NA
NA
NA
NA
NA
NA
NA
NA
NA
NA
NA

Which is not the correct answer, particularly considering that my input file only has the six lines shown above. Note that the number of lines with C, H, and other letters is variable.

What I should get is

shift
163.11
2.13
NA
NA
NA

Aucun commentaire:

Enregistrer un commentaire