Bash: How to Sort by Specific Column in File


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

You can use the following methods to do so:

Method 1: Sort by Column in Ascending Order

sort -k2 -n player_data.txt

This particular example will sort the rows of the text file named player_data.txt based on the values in column 2 in ascending (smallest to largest) order.

Method 2: Sort by Column in Descending Order

sort -k2 -nr player_data.txt

This particular example will sort the rows of the text file named player_data.txt based on the values in column 2 in descending (largest to smallest) order.

Here is what the various commands do:

  • sort: Specifies that we would like to sort the rows of the file
  • k: Stands for “key” and represents the column number to sort by, e.g. use k4 to sort by column 4
  • n: Stands for “numeric sort” and specifies that the column should be interpreted as numbers and not text, otherwise a number like “11” would come before a number like “2”
  • r: Stands for “reverse” and allows use to sort in reverse order

The following examples show how to use each method in practice with the following text file named player_data.txt that contains the information about the team name and points scored by various basketball players:

Example 1: Sort by Column in Ascending Order

We can use the following syntax to sort the rows of the file in ascending order based on the values in column 2 of the file:

sort -k2 -n player_data.txt

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

Bash sort by column

Notice that the rows are now sorted in ascending order based on the values in column 2 of the file.

Example 2: Sort by Column in Descending Order

We can use the following syntax to sort the rows of the file in descending order based on the values in column 2 of the file:

sort -k2 -nr player_data.txt

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

Bash sort by column in reverse order

Notice that the rows are now sorted in descending order based on the values in column 2 of the file.

Related Tutorials

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

Bash: How to Count Number of Unique Lines in File
Bash: How to Count Number of Characters in String
Bash: How to List All Files in Folder by Size

Leave a Reply