AIX Tip of the Week

Subject: Using "awk" to Sum Columns

Audience: All

Date: May 21, 2005

The awk* command is a powerful tool for extracting and manipulating data from a file. The following examples illustrate different ways "awk" can be used to sum columns of numbers in a file.

Example #1: Sum the first column of numbers in a file

Syntax: awk -f sum1.awk < numbers.txt
Awk file:

# sum1.awk - 
{ sum+= $1 }
END { print sum }

Example #2: Sum column 2 of lines containing string "AIX"

Syntax: awk -f filter_sum.awk < numbers.txt
Awk file:

#filter_sum.awk 
/AIX/ { sum+=$2}
END { print sum }

Example #3: Sum a specific column

Syntax: awk -f sum2.awk COL=3 < numbers.txt
Awk file:

#sum2.awk
{ sum+=$COL}
END { print sum }

Example #4: Sum all columns

Syntax: awk -f sum_all.awk < numbers.txt
Awk file:

#sum_all.awk
{   for (i=1; i<=NF; i++) { sum[i]+= $i }   }

END { for (i=1; i<=NF; i++ ) { print "Col[", i, "] =", sum[i] } }

The awk command has many more capabilities than just summing columns. Some of the ways I've used awk include

For more information search the web, and/or see the AIX URL http://publib16.boulder.ibm.com/doc_link/en_US/a_doc_lib/cmds/aixcmds1/awk.htm

* the awk command is named after its authors: Aho Weinberger Kernighan


Bruce Spencer,
baspence@us.ibm.com

May 21, 2005