Accessing fields by index in Awk

Posted: 11th August 2015 by Tim in Awk
Tags: , , , , ,

In awk, fields are accessed by number; $1 for the first field, $2 for the second, etc. But sometimes the field number you want to access is not known until run time. In these cases, you can access the field using the $(<index>) syntax. The constant NF contains the number of fields available.

For example, you can print all fields with their field index like so:

echo "Hello, World" | awk '{ for (i = 1; i <= NF; ++i) { print i, $(i); } }'

The code above will print:

1 Hello,
2 World