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 purpose of the shebang line, and what does #!/bin/bash do? [Basic]
- What is the difference between sh and bash? [Basic]
- How do you make a script executable and run it? [Basic]
- What is the difference between running a script with ./script.sh, bash script.sh, and source script.sh? [Basic]
- What does sourcing a script do differently from executing it? [Basic]
- How do you declare a variable in Bash, and why are spaces around = not allowed? [Basic]
- What is the difference between $var and ${var}? [Basic]
- What is the difference between single quotes and double quotes in Bash? [Basic]