Low Orbit Flux Logo 2 D

AWK How To Sum A Column

Summing a column is easy with awk.

Assume we have a text file that looks like this. You might have noticed that one row contains letters instead of numbers. Don’t worry about that. Those will be excluded automatically.

data.txt
1 2 3 4 4 3 2 1 5 6 7 8 8 7 6 5 1 5 6 2 abc xyz edw abc

You can run the following to add up every number in column four:


awk '{c+=$4} END{print c}' data.txt 

This is the result:


20

You can sum multiple columns like this:


awk '{c1+=$1; c2+=$2; c3+=$3; c4+=$4;} END{print c1, c2, c3, c4}' data.txt 

This would be the result:


19 23 24 20

Here is another example. This isn’t exactly a useful example but it shows how this might work.


ps -ef | awk '{c+=$4} END{print c}'