gpt4 book ai didi

macos - awk 模式中的十六进制文字

转载 作者:行者123 更新时间:2023-12-04 23:53:04 26 4
gpt4 key购买 nike

awk 能够将字段解析为十六进制数:

$ echo "0x14" | awk '{print $1+1}'
21 <-- correct, since 0x14 == 20

但是,它似乎不处理带有十六进制文字的操作:
$ echo "0x14" | awk '$1+1<=21 {print $1+1}' | wc -l
1 <-- correct
$ echo "0x14" | awk '$1+1<=0x15 {print $1+1}' | wc -l
0 <-- incorrect. awk is not properly handling the 0x15 here

有解决方法吗?

最佳答案

您在这里处理两个相似但不同的问题,awk 中的非十进制数据您的 awk 中的输入和非十进制文字程序。

the POSIX-1.2004 awk specification , 词汇约定:

8. The token NUMBER shall represent a numeric constant. Its form and numeric value [...]
with the following exceptions:
a. An integer constant cannot begin with 0x or include the hexadecimal digits 'a', [...]

所以 awk (大概你正在使用 nawkmawk )行为“正确”。 gawk (从 3.1 版开始)默认支持非十进制(八进制和十六进制)文字数字,尽管使用 --posix正如预期的那样,开关将其关闭。

在这种情况下,正常的解决方法是使用定义的数字字符串行为,其中数字字符串将被有效地解析为 C 标准 atof() strtod() 功能,支持 0x - 前缀数字:
$ echo "0x14" | nawk '$1+1<=0x15 {print $1+1}'
<no output>
$ echo "0x14" | nawk '$1+1<=("0x15"+0) {print $1+1}'
21

这里的问题是这不太正确,如 POSIX-1.2004 also states :
A string value shall be considered a numeric string if it comes from one of the following: 
1. Field variables
...
and after all the following conversions have been applied, the resulting string would
lexically be recognized as a NUMBER token as described by the lexical conventions in Grammar

更新: gawk目标是“2008 POSIX.1003.1”,但请注意,因为 2008 版(参见 IEEE Std 1003.1 2013 edition awk here)允许 strtod()和实现相关的行为,不需要数字符合词汇约定。这应该(隐式)支持 INFNAN也。 Lexical Conventions 中的文本也做了类似的修改,以允许使用 0x 的十六进制常量。前缀。

这不会像 gawk 中希望的那样表现(考虑到数字的词汇限制)。 :
$ echo "0x14" | gawk  '$1+1<=0x15 {print $1+1}'
1

(注意“错误”的数字答案,它会被 |wc -l 隐藏)
除非你使用 --non-decimal-data也:
$ echo "0x14" | gawk --non-decimal-data '$1+1<=0x15 {print $1+1}'
21

也可以看看:
  • https://www.gnu.org/software/gawk/manual/html_node/Nondecimal_002dnumbers.html
  • http://www.gnu.org/software/gawk/manual/html_node/Variable-Typing.html

  • 这个接受的答案 SE question有一个可移植性的解决方法。

    为非十进制数提供两种类型支持的选项是:
  • 仅使用 gawk , 没有 --posix并与 --non-numeric-data
  • 实现一个包装函数来执行十六进制到十进制,并将其与您的文字和输入数据一起使用

  • 如果您搜索“awk dec2hex”,您可以找到后者的许多实例,一个可以通过的实例在这里: http://www.tek-tips.com/viewthread.cfm?qid=1352504 .如果你想要类似 gawk 的 strtonum() ,你可以得到一个便携的 awk-only 版本 here .

    关于macos - awk 模式中的十六进制文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19510107/

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