在 awk 中转换为 int
我正在寻找一种在 awk 中将字符串转换为 int 的方法。我有以下似乎正在进行字符串比较
(注意:字段$5
是两种格式之一的百分比: 80%
或 9.0%
)
awk '{if (substr($5,1,(length($5)-1)) >= 90) ...
因此,当我将其更改为:
awk '{if (substr($5,1,(length($5)-1))+0 >= 90+0 ) ...
它与我的预期进行比较时。这是合适的演员阵容吗?有没有“更好”的方式来表演演员?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
大多数新 awks 都有一个 int() 函数。
但是,“The Awk 编程语言”中记录的转换方法是通过使用 numericValue 和
+0
来显示的。我手头没有这本书,但我认为您也可以使用+0.0
转换为浮点值。我希望这有帮助。
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.
您可以只使用+0。假设变量
v
是您的百分比值。您不必删除
%
符号。You can just use +0. say variable
v
is your percentage value.You do not have to get rid of the
%
sign.根据文档,
int(x)< /code> 符合 POSIX 标准。该数字仍然是浮点数(因为 awk 中的所有数字都是浮点数),但它将被截断为 int。
添加 0 不会将字符串转换为 int。它将把它转换为浮点数。
如果您有一个基于 The One True AWK 的旧
awk
作者:Brian Kernighan,例如 macOSawk
或 FreeBSDawk
,您将看到 :要强制将表达式视为数字,请在其中添加 0
如果您不关心浮点数并且有
gawk
您还可以使用strtonum< /code>
其他来源:
OS X 版本的 AWK,源自 Brian Kernighan 的“The One True AWK”
awk
中的所有数字都是浮点型:搜索“所有算术都应遵循 ISO C 标准指定的浮点算术语义”
搜索“awk 中的所有数字都是浮动的”
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 macOSawk
or FreeBSDawk
, you will see this at the bottom of the manpage: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 usestrtonum
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"