Sunday, October 30, 2022

[SOLVED] Comparing numbers with awk

Issue

EDIT: found the answer thanks to James Brown, there was a problem in the way I formatted the command:

awk -F"," '{ if ($2*$3 > 0.5) print }'

is working.

I've got a file like this:

1000,0.5,1
2000,0.5,3
4000,1,3
5000,0.2,1

I need to multiply $2 and $3 for each line and check if the result is superior to 0.5. I read that the -gt operator cannot handle floating-point numbers and that awk could do it.

Here's the best I could come up with:

cat awk.txt | awk -F"," '{ if ("$2"*"$3" > "0,5") print "$line"}'

Of course, it doesn't work, but it doesn't return any error...

Expected result:

5000,0.2,1

Can you point me in the right direction?

Thank you very much


Solution

After fixing the errors in your code:

$ awk -F"," '{if($2*$3 > 0.5) print}' file

output is:

2000,0.5,3
4000,1,3

You could also just:

$ awk -F, '$2*$3>0.5' file


Answered By - James Brown
Answer Checked By - Marilyn (WPSolving Volunteer)