linux - awk数组下标转换的规则是什么?

标签 linux unix awk gawk

我知道了,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[""]的值是 NULLarray["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/

相关文章:

ruby-on-rails - 已部署 Rails3 但未显示在服务器之外

c - 哪些部分构成可执行文件的大小?

c++ - 如何从 ltrace 获取 C++ 堆分配的虚拟方法名称?

linux - 是否可以创建一个脚本来保存和恢复权限?

regex - Linux bash : sed, awk 等工具将行尾正则表达式 '$' 匹配为终端宽度

linux - 为什么Linux不需要驱动程序

unix - 从 Bash 脚本在线程中运行 UNIX 命令

unix - 在 X 行和 X 字段中插入变量值 UNIX BASH

ruby - Grep 文件并在 ruby​​ 中提取值

awk - awk 中 $1 和 $2 的用法