How to Use awk to Print Last Line of a File


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

You can use the following syntax to do so:

awk 'END{print}' player_stats.txt

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

Note that sometimes you may wish to print the first line of the file as well if it contains a header row. You can use the following syntax to print this first header row along with the last line of the file:

awk 'NR==1 {first = $0} END {print first; print}' player_stats.txt

The following example shows how to use each of these methods in practice.

Example: Use awk to Print Last Line of a File

Suppose we have the following text file named player_stats.txt that contains information about statistics for various basketball players:

Suppose that we would like to print only the last line of the file.

We can use the following syntax to do so:

awk 'END{print}' player_stats.txt

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

awk print last line in file

Notice that this prints only the last line in the file.

If you would like to first print the header row from the file along with the last row, then you can use the following syntax:

awk 'NR==1 {first = $0} END {print first; print}' player_stats.txt

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

awk print first and last line in file

Notice that this prints the header row along with the last row in the file.

Related Tutorials

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

How to Use awk to Print All Fields Except First Field
How to Use awk to Print Last Column of File
How to Use awk to Extract Substring

Leave a Reply