【问题标题】:Not able to build an array & print it out in AWK无法构建数组并在 AWK 中打印出来
【发布时间】:2022-01-08 18:09:14
【问题描述】:

我正在为一些琐碎的事情撞墙,但我不知道为什么它不允许我通过在 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[$1]=$0; next } { for (index=0; index<=FS; index++)  print index ":" employee[index] }' Employee.txt
awk: cmd. line:1: BEGIN { FS="|" } { employee[$1]=$0; 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[$1]=$0 } END { for (index in employee) { print employee[index] } }' Employee.txt

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

【问题讨论】:

  • 请将该示例输入的所需输出(无描述、无图像、无链接)添加到您的问题(无评论)。
  • index&lt;=FS这里应该是一些数值所以可能是index&lt;=NF
  • 所需的输出是逐行打印Employee.txt。这似乎是一个语法错误,但我无法弄清楚它是什么。谢谢,
  • 更改索引后出现同样的错误
  • 试试这个:awk 'BEGIN { FS="|" } { employee[NR]=$0 } END { for (i=1; i&lt;=NR; i++) print employee[i] }' file

标签: unix awk aix


【解决方案1】:

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[$1]=$0; 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 中测试)

【讨论】:

  • 我们不再遇到语法错误,但它只打印出 inx 的值后跟冒号,而不是 Employee.txt 记录。 1:2:3:4:.......谢谢
  • RavinderSingh13 的解决方案对我来说效果很好。我得到和他一样的输出,而不是乔治杰克逊得到的输出。
  • 下面的for循环仍然只打印出员工编号。后跟一个冒号:awk 'BEGIN { FS="|" } { 雇员[$1]=$0;下一个 } END { for (inx=1; inx
  • 此 for 循环有效:awk 'BEGIN { FS="|" } { employee[NR]=$0 } END { for (i in employee) { print i ":" employee[i] } }' Employee.txt
  • FWIW index 通常缩写为 idx,而不是 inx。在 40 年的编程生涯中,我想我从未见过它缩写为 inx
猜你喜欢
  • 2013-04-04
  • 1970-01-01
  • 1970-01-01
  • 2012-09-13
  • 2020-04-14
  • 2021-03-25
  • 1970-01-01
  • 2014-03-24
  • 2017-11-05
相关资源
最近更新 更多