awk: illegal reference to array a

匿名 (未验证) 提交于 2019-12-03 00:57:01

问题:

I am trying to use this awk command:

awk -F: ' FILENAME==ARGV[1] {      a[FNR]=$1 } FILENAME==ARGV[2] {      for(i=1;i<=length(a);i++) {          if(match($0,a[i])) {              print a[i],$1         }     } }' 16.passwd 16.group | sort 

But got:

awk: line 1: illegal reference to array a 

回答1:

Your problem is this:

length(a) 

Using length(array) to get the number of elements in an array is a GNU awk extension and apparently you aren't using GNU awk. Change:

for(i=1;i<=length(a);i++) 

to

for(i=1;i in a;i++) 

and it should work.



回答2:

I did not see anything wrong with your script, as far as syntax goes. I saved your code in a file called script.awk, and executed:

awk -F: -f script.awk file1 file2 

and did not see any error. Why don't you try the same: put your script in a separate file and invoke awk on it. If you still have the same problem, I suspect the problem might be in the data file.

Update

I cleaned up the code a little, the new version may be easier to read:

FNR==NR {a[FNR] = $1; next}  {     for (i in a) {         if (match($0, a[i])) {             print a[i], $1         }     } } 


回答3:

I got this issue. Script worked on old server and stop to work on a new one.

Issue was that old server had 'gawk' installed, and new one has 'mawk', which does not support arrays.

I solved it by sudo apt-get install gawk.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!