Bash: How to Sort by Last Column in File


Often you may want to use Bash to sort data by the last column in a file.

You can use the following basic syntax to do so:

awk '{print $NF,$0}' players.txt | sort -n | cut -f2- -d' '

This particular example will sort the rows of the file named player_data.txt based on the values in the last column of the file.

Here is how this code works:

  • First, we use $NF to get “number of fields” from the file, which extracts the last field
  • Then we use the print command to add the last field to the beginning of the file
  • Then we use the sort command with -n (numeric sort) to sort the file based on the values in the last column (which is currently at the beginning of the file)
  • Then we use cut to extract only the columns from column number 2 to the end of the file, using the -d flag to specify that a space should be used as a delimiter

This syntax allows us to sort the rows of the file based on the values in the last column.

The following example shows how to use this syntax in practice.

Example: Use Bash to Sort by Last Column in File

Suppose that we have a text file named player_data.txt that contains information about various basketball players:

Suppose that we would like to sort the rows based on the values in the last column (the “rebounds” column) of the file.

We can use the following syntax to do so:

awk '{print $NF,$0}' players.txt | sort -n | cut -f2- -d' '

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

Bash sort by last column

Notice that the rows are sorted in ascending order based on the values in the last column.

Note: If the last column of your file contains text values then you can leave out the -n flag when using the sort command. You only need to specify -n if the last column is numeric.

Related Tutorials

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

Bash: How to Sort File by Multiple Columns
Bash: How to Count Number of Unique Lines in File
Bash: How to Count Number of Characters in String

Leave a Reply