How to Use awk to Sum the Values in a Column


Often you may want to use awk to sum the values in a particular column of a file.

You can use the following basic syntax to do so:

awk '{sum+=$2;} END{print sum;}' players.txt

This particular example will calculate the sum of the values in column 2 of the file named players.txt.

Note that we define a variable named sum to hold the running sum of values in column 2 ($2) of the file and then use the print command to print the final sum.

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

Example: How to Use awk to Sum the Values in a Column

Suppose we have a file named players.txt 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 sum the values in column 2 (the “points” column) of the file.

We can use the following syntax to do so:

awk '{sum+=$2;} END{print sum;}' players.txt

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

awk sum values in column

Notice that this returns a value of 146, which represents the sum of values in column 2 of the file.

We can confirm that this is correct by manually calculating the sum of values in column 2:

Sum of values: 22 + 19 + 20 + 40 + 13 + 10 + 22 = 146

Feel free to change the $2 in the code to a different number to calculate the sum of a different column in the file.

Note: If you attempt to calculate the sum of values for a column that contains characters, then this syntax will simply return 0 as a result.

Related Tutorials

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

How to Use awk to Print All Columns After Specific Number
How to Use awk to Print Rows Where Column Equals Value
How to Use awk to Print Last Line of a File
How to Use awk to Print a Range of Columns

Leave a Reply