Bash: How to Extract Specific Columns from CSV File


Often you may want to use Bash to extract specific columns from a CSV file.

You can use the following methods to do so:

Method 1: Extract One Specific Column from CSV File

cat nba_data.csv | cut -d ',' -f2

This particular example extracts column 2 from the CSV file named nba_data.csv.

Note that we use cut to filter using a -d delimiter of a comma and -f to specify the field (column) to select the value from.

Method 2: Extract Multiple Specific Columns from CSV File

cat nba_data.csv | cut -d ',' -f1,3

This particular example extracts columns 1 and 3 from the CSV file named nba_data.csv.

The following example shows how to use each method in practice with the CSV file named nba_data.csv that contains the following content:

Notice that this file contains three columns that contain information about various basketball players.

Example 1: Extract One Specific Column from CSV File in Bash

Suppose that we would like to extract only the second column (the “points” column) from the CSV file named nba_data.csv.

We can use the following syntax to do so:

cat nba_data.csv | cut -d ',' -f2

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

Bash extract one specific column from CSV file

Notice that this returns only the values from the points column in the CSV file, which represents the second column in the file.

By specifying -f2 we were able to extract only column 2 from the file.

Example 2: Extract Multiple Specific Columns from CSV File in Bash

Suppose that we would like to extract only the first and third column (the “team” and “assists” columns) from the CSV file named nba_data.csv.

We can use the following syntax to do so:

cat nba_data.csv | cut -d ',' -f1,3

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

Bash extract several specific columns from CSV file

Notice that this returns only the values from the team and assists column in the CSV file, which represent the first and third columns in the file.

By specifying -f1,3 we were able to extract only columns 1 and 3 from the file.

Related Tutorials

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

Bash: How to Read Columns from CSV File into Arrays
Bash: How to Read CSV File and Skip First Line
Bash: How to Replace All Occurrences of String in File

Leave a Reply