Skip to content
Latchkey

awk NF: Count and Use the Field Count

awk NF is the count of fields in the current record, so $NF is the last field and NF can filter malformed lines.

NF lets you reach the last column without counting and reject lines that have the wrong shape, which is handy when tool output is ragged.

What it does

NF is a built-in variable equal to the number of fields awk found on the current line after applying FS. $NF references the last field, $(NF-1) the second to last. Assigning to NF truncates or extends the record.

Common usage

Terminal
# print the last field of every line
awk '{print $NF}' access.log
# only lines that have exactly 5 fields
awk 'NF==5' report.txt
# skip blank lines (NF is 0 on a blank line)
awk 'NF' input.txt
# print second-to-last column
awk '{print $(NF-1)}' data.txt

Patterns

ExpressionWhat it does
$NFThe last field
$(NF-1)The second-to-last field
NFAs a pattern: true (non-zero) on any non-blank line, so it drops blank lines
NF==3Match lines with exactly three fields
NF>=2Match lines with at least two fields
NF=2Assignment: truncate the record to its first two fields

In CI

NF as a bare pattern (awk 'NF') is a compact way to strip blank lines from log output before further processing. To grab the last token of a status line, $NF beats hard-coding a column number that shifts when a tool changes its format.

Common errors in CI

Writing $NF-1 (no parentheses) means "value of the last field minus one", not the second-to-last field; use $(NF-1). Assigning NF=0 in gawk empties the line, which can silently blank your output. Lines split on the wrong FS report the wrong NF, so confirm -F before trusting field counts.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →