Bash: How to Find Minimum and Maximum Value of Column


You can use the following syntax in Bash to calculate the minimum value in a specific column of a file:

cut -d " " -f2 team_data.txt | sort -nr | tail -n1

And you can use the following syntax to calculate the maximum value in a specific column of a file:

cut -d " " -f2 team_data.txt | sort -n | tail -n1

These particular examples will calculate the minimum and maximum values in the second column of the file named team_data.txt.

Here is what the various commands do:

  • cut -d ” ” -f2: Return only “field 2” (-f2) of the file, using a space as a delimiter (-d)
  • sort -n: Sort the values of field 2, specify that the values should be interpreted as numbers (-n)
  • tail -n1: Only return the last value

Note: By using sort -nr we are able to sort by numeric values in reverse order.

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

Related: How to Calculate the Average of a Column in Bash

Example: How to Calculate Minimum and Maximum of Column in Bash

Suppose we have a file named team_data.txt that contains information about various basketball teams, including:

  • The team name
  • The total points scored by the team
  • The total assists recorded by the team

First, we can use the cat command to view the contents of this file:

We can use the following syntax to calculate the minimum value of the second column in the file:

cut -d " " -f2 team_data.txt | sort -nr | tail -n1

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

Bash find minimum value in column

This returns a value of 78, which represents the minimum value in the second column of the file.

We can then use the following syntax to calculate the maximum value of the second column in the file:

cut -d " " -f2 team_data.txt | sort -n | tail -n1

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

Bash find minimum and maximum value in column

This returns a value of 103, which represents the maximum value in the second column 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 Count Number of Columns in File

Leave a Reply