无法构建数组并在 AWK 中打印出来

Not able to build an array & print it out in AWK

我正在为一些琐碎的事情撞墙,但我不知道为什么它不允许我通过在 AIX 上打印回文件之前读取文件中的每一行来构建数组 6.x.

Employee.txt
1|Sam|Smith|Seatle
2|Barry|Jones|Seatle
3|Garry|Brown|Houston
4|George|Bla|LA
5|Celine|Wood|Atlanta
6|Jody|Ford|Chicago

bash-4.3$ awk 'BEGIN { FS="|" } { employee[]=[=10=]; next } { for (index=0; index<=FS; index++)  print index ":" employee[index] }' Employee.txt
awk: cmd. line:1: BEGIN { FS="|" } { employee[]=[=10=]; next } { for (index=0; index<=FS; index++)  print index ":" employee[index] }
awk: cmd. line:1:                                                                                                                   ^ syntax error
awk: cmd. line:1: error: invalid subscript expression

使用不同的 for 循环时出现同样的错误。

bash-4.3$ awk 'BEGIN { FS="|" } { employee[]=[=11=] } END { for (index in employee) { print employee[index] } }' Employee.txt

awk: cmd. line:1: BEGIN { FS="|" } { employee[]=[=11=] } END { for (index in employee) { print employee[index] } }
awk: cmd. line:1:                                                                                                ^ syntax error
awk: cmd. line:1: error: invalid subscript expression

index 是内置的 GNU AWK 函数,因此当您尝试将其用作数组键时会出现语法错误。将 index 更改为 inx 以避免语法错误并对最后一个操作应用一些更改以获得所需的输出

file.txt内容为

1|Sam|Smith|Seatle
2|Barry|Jones|Seatle
3|Garry|Brown|Houston
4|George|Bla|LA
5|Celine|Wood|Atlanta
6|Jody|Ford|Chicago

然后

awk 'BEGIN { FS="|" } { employee[]=[=11=]; next } END{ for (inx=1; inx<=NR; inx++){print inx ":" employee[inx]} }' file.txt

输出

1:1|Sam|Smith|Seatle
2:2|Barry|Jones|Seatle
3:3|Garry|Brown|Houston
4:4|George|Bla|LA
5:5|Celine|Wood|Atlanta
6:6|Jody|Ford|Chicago
7:

解释:将index更改为inx,将for的检查更改为更少的行数(NR),将最后一个操作注册为END(处理完所有文件后执行)。请注意,for for Arrays 可能比 for 更适合您使用的内容,具体取决于您的要求。

(在 gawk 4.2.1 中测试)