user2452340
user2452340

Reputation: 1505

awk: illegal reference to array a

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

Upvotes: 9

Views: 7295

Answers (3)

George Shuklin
George Shuklin

Reputation: 7907

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.

Upvotes: 5

Ed Morton
Ed Morton

Reputation: 203995

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.

Upvotes: 14

Hai Vu
Hai Vu

Reputation: 40763

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
        }
    }
}

Upvotes: 1

Related Questions