gpt4 book ai didi

bash - awk求和不带浮点精度

转载 作者:行者123 更新时间:2023-11-29 09:17:28 29 4
gpt4 key购买 nike

我有一个file.txt,我正在尝试总结第四列和第五列的值:

^20170821^3007030^153^863.53^0.42^
^20170821^1402675^110^581.36^0.37^
^20170821^1404785^24^155.29^0.29^
^20170821^1406505^40^210.51^0.00^
^20170821^1005^1^18.00^0.00^
^20170821^9657^7^7.28^0.00^
^20170821^143646^86^486.59^0.08^
^20170821^342657^3^12.60^0.00^
^20170821^1006^4^7.04^0.04^
^20170821^1004^1215^3502.44^12.09^
^20170821^1007^932^6689.64^15.07^
^20170821^378228^1^2.80^0.00^
^20170821^704797^4^23.80^0.00^
^20170821^705642^2^9.80^0.00^
^20170821^703689^7^40.60^0.00^
^20170821^148340^75^382.81^0.20^
^20170821^257^2^5.60^0.00^
^20170821^3702^1^2.80^0.00^
^20170821^3703^1^7.00^0.00^
^20170821^258^1^7.00^0.00^
^20170821^920299^11^60.20^0.00^
^20170821^210705^2^14.00^0.00^
^20170821^867693^12^65.88^0.08^
^20170821^2635085^6^33.60^0.00^
^20170821^13211^140^409.18^0.58^
^20170821^64^2^14.00^0.00^
^20170821^13214^234^1685.91^1.26^
^20170821^13212^2^34.90^0.00^
^20170821^13213^2^2.80^0.00^
^20170821^18385^8^7.28^0.00^


$awk -F '^' '{sum += $5} END {print sum}' file.txt

我得到以下结果:15344.2

 $awk -F '^' '{sum += $6} END {print sum}' file.txt

我得到以下结果:30.48

然后我在 Excel 中检查了结果。原来是awk加法第一次加错了。缺少 0.04

enter image description here

如何正确求和列?

最佳答案

当您可以使用带格式修饰符的 printf() 时,不要通过在 Awk 中使用 print 来保留浮点精度。例如。对 printf 做同样的事情,2 位精度控制,如下所示

awk -F '^' '{ sum += $5 } END { printf "%0.2f",sum }' file
15344.24

来自 GNU Awk - Modifiers for printf Formats在部分精度状态下,

.prec

A period followed by an integer constant specifies the precision to use when printing. The meaning of the precision varies by control letter:


作为旁注,您可以将 print 语句与特殊的 awk 变量 OFMT 一起使用,如下所述,

GNU Awk - Controlling Numeric Output with print

The predefined variable OFMT contains the format specification that print uses with sprintf() when it wants to convert a number to a string for printing. The default value of OFMT is "%.6g". The way print prints numbers can be changed by supplying a different format specification for the value of OFMT

通过这种方式,您的示例可以修改为在 BEGIN 子句中定义 OFMT 以使用两位数精度控制进行打印,即

awk -F '^' 'BEGIN { OFMT="%.2f" }{ sum += $5 } END { print sum }' file
15344.24

此选项适用于所有 POSIX compliant Awk版本。

关于bash - awk求和不带浮点精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45815755/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com