Home > Software design >  Not able to build an array & print it out in AWK
Not able to build an array & print it out in AWK

Time:12-03

I am hitting my head against the wall for something trivial, yet I don’t know why it is not allowing me to build an array by reading each row from a file before printing it back out on 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

Got the same error using a different for loop.

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

CodePudding user response:

index is built-in GNU AWK function, thus you have syntax error when you try to use it as array key. Change index to inx to avoid syntax error and apply some changes to last action to get desired output

Let file.txt content be

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

then

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

output

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:

Explanation: changed index to inx, change for's check to less equal number of rows (NR), register last action as END (execute after processing all files). Note that for for Arrays might be better fit for that rather than for you have used depending on your requirements.

(tested in gawk 4.2.1)

  • Related