Category Archives: AWK

A Less AWKward For Loop

When writing an AWK script, many people who come from C background write the for loop for accessing an array like this:

for (i=1; i <= length(myarray); i++) {
    # Do something with myarray[i]
}

There is nothing wrong the the above code: it gets the job done. However, the loop feel less AWK-like and a little … AWKward. Besides, the above pattern does not work with arrays whose indices are strings, not number. A better way to write the same for loop is:

for (i in myarray) {
    # Do something with myarray[i]
}

So, stop being AWKward and start coding your for loop the AWK way.

Advertisements