I'm looking for a method to cast a string to an int in awk. I have the following which appears to be doing a string comparison
(note: field $5
is a percentage in one of two formats: 80%
or 9.0%
)
awk '{if (substr($5,1,(length($5)-1)) >= 90) ...
So, when I change it to:
awk '{if (substr($5,1,(length($5)-1))+0 >= 90+0 ) ...
It compares as I intended. Is this an appropriate cast? Is there a 'better' way to perform the cast?
Most new awks have an int() function.
But the method for casting documented in 'The Awk Programming Language' is shown as you do it, by using numericValue and +0
. I don't have the book handy, but I think you can also cast for float value by using +0.0
.
I hope this helps.
You can just use +0. say variable v
is your percentage value.
$ awk -v v="80.1%" 'BEGIN{print v+0.1}'
80.2
You do not have to get rid of the %
sign.
According to the docs, int(x)
is POSIX compliant. The number will still be a float (since all numbers in awk are floating-point) but it will be truncated to an int.
Adding 0 won't convert a string into an int. It will convert it to a float.
If you have an old awk
based on The One True AWK by Brian Kernighan, such as macOS awk
or FreeBSD awk
, you will see this at the bottom of the manpage:
BUGS
There are no explicit conversions between numbers and strings. To force
an expression to be treated as a number add 0 to it; to force it to be
treated as a string concatenate "" to it.
The scope rules for variables in functions are a botch; the syntax is
worse.
To force an expression to be treated as a number add 0 to it
If you don't care about floats and you have gawk
you can also use strtonum
Other sources:
OS X version of AWK, which is derived from "The One True AWK” by Brian Kernighan
All numbers in awk
are floating-point:
Search "All arithmetic shall follow the semantics of floating-point arithmetic as specified by the ISO C standard"
Search "all numbers in awk are floating"
精彩评论