Addition Operation Using AWK In Bash Script

Suppose we have text file like this :

tedy@tedy-laptop:~$ cat test.txt
20090924100104 Rejected 0 at 237 CAPS
20090924100105 Rejected 0 at 237 CAPS
20090924100106 Rejected 0 at 234 CAPS
20090924100107 Rejected 0 at 233 CAPS
20090924100108 Rejected 0 at 235 CAPS
20090924100109 Rejected 0 at 226 CAPS
20090924100110 Rejected 0 at 242 CAPS
20090924100111 Rejected 0 at 248 CAPS
20090924100112 Rejected 0 at 227 CAPS
20090924100113 Rejected 0 at 253 CAPS
20090924100114 Rejected 0 at 216 CAPS
20090924100115 Rejected 0 at 252 CAPS
20090924100116 Rejected 0 at 222 CAPS
20090924100117 Rejected 0 at 288 CAPS
20090924100118 Rejected 0 at 238 CAPS
20090924100119 Rejected 0 at 229 CAPS

If we want to sum all number in the fifth column, we can do it by using awk command like this :

tedy@tedy-laptop:~$ cat test.txt | awk '{SUM += $5}{print SUM}' | tail -1
3817
tedy@tedy-laptop:~$

Or we can use other dummy method like this :

tedy@tedy-laptop:~$ j=0
tedy@tedy-laptop:~$ for i in `cat test.txt | awk '{print $5}'`
> do
> j=$((j+i))
> done
tedy@tedy-laptop:~$ echo $j
3817
tedy@tedy-laptop:~$

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.