Bash: How to Count Number of Columns in File


Often you may want to use Bash to count the number of columns in a particular file.

You can use the following methods to do so:

Method 1: Count Number of Columns in Text File

awk '{print NF}' teams.txt | sort -nu | tail -n 1

This particular example will return the total number of columns in the text file named teams.txt.

Note: We used tail -n 1 to return the highest column count for a given row. This is useful if not every row has the same number of columns.

Method 2: Count Number of Columns in CSV File

awk -F',' '{print NF}' player_data.csv | sort -nu | tail -n 1

This particular example will return the total number of columns in the CSV file named player_data.csv.

Note: We used -F’,’ to specify that a comma should be used as a delimiter when reading the file.

The following examples show how to use each method in practice.

Example 1: Count Number of Columns in Text File

Suppose we have a file named teams.txt that contains information about various basketball teams.

We can use the cat command to view the contents of the file:

We can use the following syntax to count the number of columns in this file:

awk '{print NF}' teams.txt | sort -nu | tail -n 1

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

Bash count columns in file

This returns a value of 3, which tells us that there are 3 total columns in the text file.

Example 2: Count Number of Columns in CSV File

Suppose we have a file named player_data.csv that contains information about various basketball players.

We can use the cat command to view the contents of the file:

We can use the following syntax to count the number of columns in this file:

awk -F',' '{print NF}' player_data.csv | sort -nu | tail -n 1

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

Bash count columns in CSV file

This returns a value of 3, which tells us that there are 3 total columns in the CSV 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