How to Use awk to Print First Column of File


Often you may want to use awk to print only the first column of a file.

You can use the following basic syntax to do so:

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

This particular example prints only the first column of the CSV file named nba_data.csv.

Here is what the various awk commands do:

  • -F, specifies that the input delimiter is a comma.
  • OFS=”,” specifies that the printed output delimiter should be a comma
  • $1 specifies that only column 1 should be printed

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

Example: How to Use awk to Print First Column of File

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

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

Suppose that we would like to print only the first column of the file.

We can use the following syntax to do so:

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

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

awk print first column

Notice that this prints only the first column from the file, which is the column that contains the team names.

Note that you could also change $1 to a different number to instead print a different column number from the file.

Also note that you can likely leave out the -F, syntax if you’re working with a text file instead because the default delimiter used for input files is one or more spaces.

Related Tutorials

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

How to Use awk to Replace newline with Space
How to Use awk to Replace All Occurrences of String in File
How to Use awk to Extract Substring

Leave a Reply