Search code examples
bashawksedgrepcut

Dividing float point data in bash


I have a data file (input.dat) in two columns, something like this

 5.12  .5
 4.1   93.8 
.9     11.2
.58    5.3

and I want to add a constant (for example 5.3) to second column values.

I did awk '{print $1, $2 + 5.3 }' < input.dat > output.dat

and it worked perfectly, output.dat looked as

 5.12  5.8
 4.1   99.1 
 .9    16.5
 .58   10.6

but when I said a=5.3 and did:

awk '{print $1, $2 + $a }' < input.dat > output.dat

something completely crazy happened to output.dat:

5.12  5.62
4.1   97.9 
.9     12.1
.58    5.88

Can someone please tell me what happened, I assume the problem was with the print which only expects $1, $2, $3 etc. I think the solution to my problem is possible if I write variable a in third column of input.dat file and then do awk '{ print $1, $2+$3 }, but what is the proper way to do floating point arithmetic operations on columns in bash?


Solution

  • Do

    awk -v a=5 '{print $1,$2+a}' input.dat