我知道了,awk
的下标数组必须是字符串。
[root@localhost]# awk 'END {array[A0]="empty"; print array[""]}'
empty
所以在上面的命令行中,因为 A0
未引用为 "A0"
,它代表一个变量。因为变量A0
之前没有设置过值,值为""
。所以print array[""]
输出empty
.
但在以下命令中:
[root@localhost]# awk 'END {array[0]="empty"; print array[""], array["0"]}'
empty
array[""]
的值是 NULL
而array["0"]
是 "empty"
。根据我的理解,这是因为变量不能以数字开头, array[0]
转换为array["0"]
默认情况下。这样对吗? awk
的下标转换规则是什么数组?
最佳答案
awk 中的数组下标是字符串,因此当您使用表达式作为数组下标时,它会被转换为字符串(如果它还不是字符串)。 0
是一个数字,而不是变量,因此以下内容适用(来自 POSIX ):
A numeric value that is exactly equal to the value of an integer (see Concepts Derived from the ISO C Standard) shall be converted to a string by the equivalent of a call to the sprintf function (see String Functions) with the string
"%d"
as the fmt argument and the numeric value being converted as the first and only expr argument. Any other numeric value shall be converted to a string by the equivalent of a call to the sprintf function with the value of the variable CONVFMT as the fmt argument and the numeric value being converted as the first and only expr argument. The result of the conversion is unspecified if the value of CONVFMT is not a floating-point format specification.
0
是一个整数,因此转换为字符串时会给出 "0"
,而不是 ""
。这是因为在 C 代码中,sprintf(buf, "%d", 0)
之后,buf
将包含字符串 "0"
。
至于变量名:在 awk grammar 中,变量由标记 NAME 描述。它的字典顺序如下:
9) A sequence of underscores, digits, and alphabetics from the portable character set (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 6.1, Portable Character Set), beginning with an underscore or alphabetic, shall be considered a word.
12) The token NAME shall consist of a word that is not a keyword or a name of a built-in function and is not followed immediately (without any delimiters) by the '(' character.
遵循此描述的标记是变量,最初为空,当空变量转换为字符串时,它会生成空字符串。
也就是说:
0
是一个数字a
是变量名_
是变量名a0
是变量名_0
是变量名0a
被解析为0 a
(0
和变量a
的串联)
关于linux - awk数组下标转换的规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29600603/