Celeb Glow
updates | March 23, 2026

How to compare float variables in awk?

awk -F, 'NR==FNR{c[$29]=$29;next} NF{print $29 ((c[$29]==$29)?" ":",mismatch")}' $file1 $file2

The value of 29th field, i.e., $29 in file1 was 832.9 and that of file2 was 832.9000. If I compare them they are not equal. I think it is taking as a string rather than a number.

How should I proceed?

2

1 Answer

awk compares floating point numbers:

I just wrote a new script:

paste \ <(awk -F, '{print $29}' file1 ) \ <(awk -F, '{print $29}' file2 ) \ | awk '{print $1; print $2; print ($1==$2)?"match" :"mismatch"}'

If you do not like breaks, then use printf instead of print.


Example

Input files

cat file1

12,2,12,12,12,12,3,2,53,6,5474,346,567,6578,89,7689,7,987,69869,1,4,5,4,3,4,2,6,21,832.9,9,2
12,2,12,12,12,12,3,2,53,6,5474,346,567,6578,89,7689,7,987,69869,1,4,5,4,3,4,2,6,21,12.329,9,2

cat file2

12,2,12,12,12,12,3,2,53,6,5474,346,567,6578,89,7689,7,987,69869,1,4,5,4,3,4,2,6,21,832.9000,9,2
12,2,12,12,12,12,3,2,53,6,5474,346,567,6578,89,7689,7,987,69869,1,4,5,4,3,4,2,6,21,832.9000,9,2

Output

% paste <(awk -F, '{print $29}' file1 ) <(awk -F, '{print $29}' file2 ) | awk '{print $1; print $2; print ($1==$2)?"match" :"mismatch"}'
832.9
832.9000
match
12.329
832.9000
mismatch
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy