Semi-OT: Awk

Home » CentOS » Semi-OT: Awk
CentOS 2 Comments

This is odd, and annoying. CentOS 6, current. Here’s my awk script:

{
room = substr($0, 48, 10);
arr[$2,room,$1] = $0;
}
END {
for ( i in arr ) {
for ( j in arr[i] ) {
for ( k in arr[i][j] ) {
print arr[i][j][k];
}
}
}
}

And when I run it, it complains awk -f awksort proplist7
awk: awksort:7: for ( j in arr[i] ) {
awk: awksort:7: ^ syntax error awk: awksort:8: for ( k in arr[i,j] ) {
awk: awksort:8: ^ syntax error awk: awksort:9: print arr[i][j][k];
awk: awksort:9: ^ syntax error

which makes no sense – I’ve done this a million times. Am I missing something, or is this a bug?

mark

2 thoughts on - Semi-OT: Awk

  • Note the last sentence in this paragraph from the gawk manpage:

    The in construct may also be used in a for loop to iterate over
    all the elements of an array. However, the (i, j) in array
    construct only works in tests, not in for loops.

    jl

  • I modelled your problem, just changing line 2 to “room = $3”. The data file was:
    1 2 3
    4 5 6
    7 8 9

    The problem is in the line ( i in arr ). i will be “1SUBSEP2SUBSEP3”, which makes a nonsense of the rest of the code.

    Using

    END {
    for ( a in arr ) {
    split( a, a2, SUBSEP )
    print a2[1], a2[2], a2[3]
    }
    }

    I get a sensible output. You’ll have to take it from here.
    —–BEGIN PGP SIGNATURE—