加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

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

发布时间:2020-12-14 00:30:03 所属栏目:Linux 来源:网络整理
导读:awk能够将字段解析为十六进制数字: $echo "0x14" | awk '{print $1+1}'21 -- correct,since 0x14 == 20 但是,它似乎不处理十六进制文字的操作: $echo "0x14" | awk '$1+1=21 {print $1+1}' | wc -l1 -- correct$echo "0x14" | awk '$1+1=0x15 {print $1+1}
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(可能是你正在使用nawk或mawk)表现得“正确”. 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()和依赖于实现的行为,不需要数字符合词法约定.这应该(隐含地)支持INF和NAN.类似地修改了词汇约定中的文本,以选择性地允许具有0x前缀的十六进制常量.

这不会表现得很好(考虑到对数字的词汇限制),就像gawk所希望的那样:

$echo "0x14" | gawk  '$1+1<=0x15 {print $1+1}'
1

(注意“错误的”数字答案,它将被| wc -l隐藏)
除非您使用 – 非十进制数据:

$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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读