What is $NF in awk Command
In awk
, $NF
is a special variable that represents the value of the last field in the current record being processed. The NF
built-in variable in awk
holds the total number of fields in the current record, and when you use $NF
, it directly accesses the value of the field that corresponds to that number.
Example Usage
Consider the following input file data.txt
:
Alice 30 Engineer
Bob 25 Designer
Charlie 35 Manager
You can use an awk
command to print the last field (job title) of each line:
awk '{ print $NF }' data.txt
Output:
Engineer
Designer
Manager
Explanation:
- In each line of the file
data.txt
,awk
splits the line into fields based on whitespace (the default behavior). - For the first line,
NF
would be3
(for "Alice", "30", "Engineer"), so$NF
refers toEngineer
. - For the second line, it refers to
Designer
, and for the third line, it refers toManager
.
More Examples
Print the Last Field with Line Number:
awk '{ print NR ": " $NF }' data.txt
Output:
1: Engineer
2: Designer
3: Manager
Check if the Last Field Matches a Specific Value:
awk '$NF == "Manager" { print $1 }' data.txt
Output:
Charlie
This command prints names where the last field is “Manager”.
Sum the Second Field but Only Print the Last Field:
awk '{ sum += $2 } END { print "Total age is:", sum; print "Last field in last line is:", $NF }' data.txt
Output:
Total age is: 90
Last field in last line is: Manager
Note that in the last statement, $NF
refers to the last field of the last line processed by awk
.
The $NF
variable is very useful when dealing with data where the number of fields can vary from line to line, allowing you to grab the last field dynamically.
In this video, using the awk
command and its internal variables such as $1
and $NF
, as well as combining the awk
and rev
commands, we find the first and last word in a string.