awk sum examples

Here are some awk examples to sum an integer column from a file or stdin (standard input) stream.

Data used in these examples

1
2
badval
4

Awk sum example on command line

Lines with invalid numbers are treated as 0. To sum values from stdin use the following command:

cat data1.txt | awk '{ S+=$1} END {print S}'
7
Env: GNU bash, version 4.3.11

To sum values from file use the following command:

awk '{ S+=$1} END {print S}' data1.txt
7
Env: GNU bash, version 4.3.11

Bash alias for awk sum code

Put the following line in your ~/.bash_profile

alias mysum="awk '{ S+=\$1} END {print S}'"

When you login next time, you can simply run

$ mysum data1.txt
##or 
$ cat data1.txt | mysum
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments