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
- What is the difference between NR and NF in awk? [Advanced]
- How do you use awk to sum or average a column? [Advanced]
- How do you split a string on a delimiter in Bash? [Intermediate]
- What is the difference between sed -i and sed without -i? [Advanced]
- What is an associative array, and how do you use one? [Intermediate]
- What is the difference between glob expansion and regex in the shell? [Intermediate]
- How do you check whether a command exists before using it? [Intermediate]
- How would you write a health-check script that polls a URL until it returns 200? [Advanced]