How to Use awk to Print Last Column of File


Often you may want to use awk to print only the last column of a file.

You can use the following methods to do so:

Method 1: Print Last Column of File

awk '{print $NF}' player_stats.txt

This particular example prints only the last column of the text file named player_stats.txt.

Method 2: Print Last Column of File for Rows that Meet Condition

awk '/Celtics/ {print $NF}' player_stats.txt

This particular example prints the last column of the text file named player_stats.txt only  for the rows that contain the pattern Celtics somewhere in the line.

Note that both of these examples use the NF statement in awk, which stands for “number of fields” and extracts the last field from a given line.

The following example shows how to use each of these methods in practice with the following text file named player_stats.txt that contains information about statistics for various basketball players:

Related: How to Use awk to Print First Column of File

Example 1: Use awk to Print Last Column of File

We can use the following syntax with awk to print the last column for each row in the file:

awk '{print $NF}' player_stats.txt

The following screenshot shows how to use this syntax in practice:

awk print last column

Notice that this prints the last column for each row in the file.

Example 2: Use awk to Print Last Column of File for Rows that Meet Condition

We can use the following syntax with awk to print the last column for each row in the file that contains the pattern Celtics somewhere in the line:

awk '/Celtics/ {print $NF}' player_stats.txt

The following screenshot shows how to use this syntax in practice:

awk print last column for rows that meet condition

Notice that this prints the last column for only the rows that contain the pattern Celtics somewhere in the line.

Related Tutorials

The following tutorials explain how to perform other common tasks in awk:

How to Use awk to Replace newline with Space
How to Use awk to Replace All Occurrences of String in File
How to Use awk to Extract Substring

Leave a Reply