How to Use awk to Print Rows Where Column Equals Value


Often you may want to use awk to only print the rows of a file where a specific column equals a specific value.

You can use the following syntax to do so:

awk '$1 == "Celtics" {print $2}' player_stats.txt

This particular example prints the value in column 2 of the file named player_stats.txt only for the rows where the value in column 1 is equal to “Celtics.”

Note that you could also use the following syntax to print the entire row of each row where the value in column 1 is equal to “Celtics”:

awk '$1 == "Celtics" {print}' player_stats.txt

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

Example: Use awk to Print Rows Where Column Equals Value

Suppose we have the following text file named player_stats.txt that contains information about statistics for various basketball players:

Suppose that we would like to print only the value from the second column (the “points” column) for each row where the value in the first column is equal to “Celtics.”

We can use the following syntax to do so:

awk '$1 == "Celtics" {print $2}' player_stats.txt

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

awk print column where another column equals value

Notice that this prints only the value from the second column (the “points” column) for each row where the value in the first column is equal to “Celtics.”

Note that we could also use the following syntax to print the entire row for each row where the value in the first column is equal to “Celtics”:

awk '$1 == "Celtics" {print}' player_stats.txt

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

awk print if column equals

Notice that this prints the entire row for each row where the value in the first column is equal to “Celtics.”

Related Tutorials

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

How to Use awk to Print All Fields Except First Field
How to Use awk to Print Last Column of File
How to Use awk to Print Last Line of a File
How to Use awk to Extract Substring

Leave a Reply