Bash: How to Extract the First and Last Column from File


Often you may want to use Bash to extract the first and last column from a file.

You can use the following syntax to do so:

awk '{print $1, $NF}' team_info.txt

This particular example will extract the first and last column from the file named team_info.txt.

Note that this method uses awk with the $1 and $NF (“number of fields) commands to extract the first and last columns from the file, assuming the delimiter is one or more spaces.

If your file uses a different delimiter, then you can use the -F parameter to specify it.

For example, you could use the following syntax to extract the first and last column from a CSV file:

awk -F, '{OFS=",";print $1,$NF}' team_info.csv

By using -F, we are able to specify that the CSV file uses a comma as a delimiter between the fields.

The following example shows how to use each of these methods in practice.

Example 1: Extract First and Last Column from a Text File

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

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

We can see that there are three columns in this file.

We can use the following syntax to extract only the first and last column from the file:

awk '{print $1, $NF}' team_info.txt

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

Bash extract first and last column from file

Notice that this returns only the first and last columns from the file.

Example 2: Extract First and Last Column from a CSV File

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

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

We can see that there are four columns in this file.

We can use the following syntax to extract only the first and last column from the file:

awk -F, '{OFS=",";print $1,$NF}' team_info.csv

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

Bash get first and last column from CSV file

Notice that this returns only the first and last columns from the CSV file.

Related Tutorials

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

Bash: How to Align Columns in Output
Bash: How to Sort File by Multiple Columns
Bash: How to Remove Specific Columns from a File

Leave a Reply