Interview Scripting (Bash, Groovy)

How does awk split lines into fields, and what are $1 and NF? [Intermediate]

Answer

awk reads input as records, normally lines, and splits each record into fields. $1 is the first field, $2 the second, $0 the whole line, and NF is the number of fields in the current record.

Technical explanation

The default field separator is runs of whitespace; use -F to set a custom separator.

awk programs have pattern-action form: condition { action }.

NF is often used to print the last field with $NF or validate record shape.

Hands-on example

echo 'api 200 15ms' | awk '{print $1, $2, $NF}'

awk -F, 'NF != 3 {print "bad row", NR, $0}' data.csv

awk '$9 >= 500 {print $1, $7, $9}' access.log

Preparing for an interview?

Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.

More Scripting (Bash, Groovy) interview questions

← All Scripting (Bash, Groovy) questions