【发布时间】:2021-08-11 12:49:32
【问题描述】:
示例输入
42 -0.400000000000000022
我想在第一列添加9'000'000'000'000'000'000,在第二列添加30。
$ echo 42 -0.400000000000000022 | awk '{ $1 += 9000000000000000000; $2 += 30 } { print }'
9000000000000000000 29.6
第 1 列计算错误,但第 2 列正常。
从文档和手册页中,有一个 --bignum 选项可以帮助我进行大整数计算。
$ echo 42 -0.400000000000000022 | awk --bignum '{ $1 += 9000000000000000000; $2 += 30 } { print }'
9000000000000000042 30
现在第 1 列可以,但第 2 列不行!
这是我的 AWK 版本,在 Ubuntu 16.04 上运行:
$ awk -V
GNU Awk 4.1.3, API: 1.1 (GNU MPFR 3.1.4, GNU MP 6.1.0)
Copyright (C) 1989, 1991-2015 Free Software Foundation.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/.
更奇怪的是,我在 Ubuntu 16.04 docker 容器中对此进行了测试,当使用 --bignum 时,两列的输出都是正确的。
我实际上不知道要寻找什么来解决这个问题。
【问题讨论】:
-
这听起来像是一个错误。 gawk 4.1.3 已经 6 年了,并且在这方面至少有 1 个已知错误(请参阅lists.gnu.org/archive/html/bug-gawk/2018-09/msg00009.html),您可以更新到当前版本 5.1.0 吗?我注意到尽管您使用
'(撇号)而不是,(逗号)作为问题文本中的千位分隔符(“我想添加9'00...”),所以您不能在C/ POSIX 语言环境 - idk 如果它会产生任何影响,但尝试在计算之前设置export LC_ALL=C以查看是否有任何区别。 -
@EdMorton 我使用
'作为千位分隔符只是为了使问题更清晰,但我没有在脚本中的任何地方使用它。但无论如何都很好!我的所有环境变量都使用fr_FR.UTF-8,在将它们更改为en_US.UTF-8后,输出很好! -
太棒了。我仍然建议您更新您的 awk 版本,以获取该错误修复以及其他增强功能。我还建议使用
LC_ALL=C(或LC_ALL=POSIX)来避免任何其他意外。