With awk, NF is known as a built-in variable. It holds a value that represents the total number of fields in the current record. When the expression $NF is used, that directly accesses the value of the field that corresponds to that number.
Consider a file named "family" with the following data:
Trev Lee Chan 71
Joe Jerome Chan 74
Jess Wayne Chan 70
Trev Eugene Chan 49
Using awk to print the value of the last field of each line (record), the command would be:
$ awk '{ print $NF }' family
The output would be:
71
74
70
49
Here's the explanation:
In each line of the file "family", awk splits the line into fields based on whitespace (the default behavior).
For the first line, NF would be 4 ( Trev, Lee, Chan, 71), so $NF refers to 71.
For the second line, NF would be 4 (Joe, Jerome, Chan, 74) so $NF refers to 74.
For the third line, NF would be 4 (Jess, Wayne, Chan, 70) so $NF refers to 70.
For the fourth line, NF would be 4 (Trev, Eugene, Chan, 49) so $NF refers to 49.
Looking at another example, to print:
- the line number of the record
- the contents of the last field
- the value NF (which esstially refers to the number of fields for that record)
$ awk '{ print " For line #", NR, "the data in field", NF, "is", $NF }' family
The output would be:
For line # 1 the data in field 4 is 71
For line # 2 the data in field 4 is 74
For line # 3 the data in field 4 is 70
For line # 4 the data in field 4 is 49
Okay, I'll stop here for now. There will be more examples forthcoming, involving the NF variable.
Great information..!
Thanks for sharing..!!
Glad you like it
It worths also mentioning the use of $(NF-1), $(NF-2) ... variables.
That represents the penultimate field, the field preceding the previous one, ...
That is handy if, for example, you are just interested with the last 3 fields independently of the number of fields in lines.
awk ' { print $(NF-2), $(NF-1), $NF } ' family
You're jumping ahead of my lesson, TM
Red Hat
Learning Community
A collaborative learning environment, enabling open source skill development.