你在这里处理两个相似但不同的问题,非十进制数据和非 - 您的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
-prefixed号码:
$ 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
UPDATE:gawk
旨在“2008 POSIX.1003。1“,但请注意,自2008版(请参阅IEEE Std 1003.1 2013 edition awk
here)允许strtod()
和实现相关的行为不需要数字符合词汇约定,这应该(隐含地)支持INF
和NAN
。中的文本Lexical约定同样修改,以便允许在十六进制常量与0x
前缀
这不会表现(上给出的数字词汇约束)相当的希望在gawk
:
$ echo "0x14" | gawk '$1+1<=0x15 {print $1+1}'
1
(注意是“错误的”数字a nswer,这已被隐藏通过|wc -l
) 除非你使用--non-decimal-data
太:
$ echo "0x14" | gawk --non-decimal-data '$1+1<=0x15 {print $1+1}'
21
参见:
此接受了答案,这SE question有一个可移植性的解决方法。
为具有两种类型的用于非十进制数字支持的选项是:
如果你搜索“AWK DEC2HEX”你可以找到后者的许多情况下,可通过一个在这里使用。如果你想要像gawk的strtonum()
这样的东西,你可以得到一个便携式awk版本here。
可能的重复:http://stackoverflow.com/questions/3683110/how-to-make-calculations-on-hexadecimal-numbers-with-awk –
@RobertoNavarro完全不同的问题。我在询问如何直接在awk命令中使用十六进制字面值(如第三个awk命令所示) – SheetJS
我一直在尝试不同的变体,如果你愿意,可以嘲笑这个,但是以为我会在我点击之前发布它去睡觉:bash $ hex = 20; echo $((16#$ hex + 1))| echo'0x''awk'{printf“%x \ n”,$ 1;}'' –