7

I have a text file employees:

Chen Cho 5/19/63 203-344-1234 $76
Tom Billy 4/12/45 913-972-4536 $102
Larry White 11/2/54 908-657-2389 $54
Bill Clinton 1/14/60 654-576-4114 $201
Steve Ann 9/15/71 202-545-8899 $58

When I do awk '$4 < 40' employees, I get:

203-344-1234
202-545-8899

It gives the same output until < 65 and when I compare $4 < 66, I get:

203-344-1234
654-576-4114
202-545-8899

I'm confused with this behaviour of awk. It seems like it's only comparing the first two digits of the field instead of throwing some error stating the comparison can't be done or something.

My question is: How is awk comparing/behaving in this case? Thank you.

1
  • Shouldn't this file be a tab delimited file?
    – IsaaC
    Apr 26 at 22:30

1 Answer 1

16

In short, this is an alphabetical comparison for GNU awk.

From GNU awk manual:

When comparing operands of mixed types, numeric operands are converted to strings using the value of CONVFMT

You can further read how this is done, following the above link, the string is created with a call to sprintf with formatting CONVFMT, which is default "%.6g" etc.

For this case, $4, 203-344-1234 is a string, not a number. And the second argument is a number, converted to the string "4", "65" etc.


Also some additional information, from the same manual page:

If, for some reason, you need to force a number to be converted to a string, concatenate that number with the empty string, "". To force a string to be converted to a number, add zero to that string

Sometimes, to ensure that a field would be used as numeric, we write it like $1+0. For example, in this case, if we force $4+0 it will be an integer with the first three digits, 203 (that's it, the attempt to create a number ended at the first non-numeric character).


See also into GNU awk manual page: String Type versus Numeric Type

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.