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.

One thought on “A Less AWKward For Loop

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s