Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk: illegal reference to array a

Tags:

awk

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
like image 404
user2452340 Avatar asked Jun 04 '13 15:06

user2452340


3 Answers

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.

like image 166
Ed Morton Avatar answered Nov 14 '22 19:11

Ed Morton


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.

like image 35
George Shuklin Avatar answered Nov 14 '22 19:11

George Shuklin


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
        }
    }
}
like image 1
Hai Vu Avatar answered Nov 14 '22 17:11

Hai Vu