Home > Mobile >  Comparing numbers with awk
Comparing numbers with awk

Time:10-31

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

CodePudding user response:

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

CodePudding user response:

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

I want to explain what actually happend

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

first thing is multiplying string $2 by string $3, this prompt GNU AWK to convert both of them to numbers as described in How awk Converts Between Strings and Numbers as neither string as whole or any prefix is valid number following does apply

Strings that can’t be interpreted as valid numbers convert to zero.

therefore you got in fact following multiplication

0*0

which yields number 0, which in turn gives following comparison

0 > "0,5"

which again prompt conversion of string to number, which gives 0 as 0 is longest number-constituting prefix of 0,5, so finally we get

0 > 0

which does never holds, so you get empty output.

  • Related