Doing math on the linux command line

I have a log file from a web server which looks like this;

1908 462
232 538
232 520
232 517

My task is to total column 1 and column 2 in a bash script. My desired output is;

2604 2037

I know of awk or sed which could go a long way to solving my problem but I can't fathom how to actually do it. I've trawled examples on Google but haven't turned up anything useful. Can someone point me in the right direction please?


awk '{a += $1; b += $2} END { print a " " b }' foo.log

(Note the complete lack of error checking.)


Ok, here's a version with error checking:

awk 'BEGIN { ok = 1 } { if (/^ *[0-9]+ +[0-9]+ *$/) { a += $1; b += $2 } else { ok = 0; exit 1 } } END { if (ok) print a, b }' foo.log

If you don't want to accept leading or trailing blanks, delete the two " *"s in the if statement.

But this is big enough that it probably shouldn't be a one-liner:

#!/usr/bin/awk -f

    ok = 1

    if (/^ *[0-9]+ +[0-9]+ *$/) {
        a += $1
        b += $2
    else {
        ok = 0
        exit 1

    if (ok) print a, b

There's still no overflow or underflow checking, and it assumes that there will be no signs. The latter is easy enough to fix; the former would be more difficult. (Note that awk uses floating-point internally; if the sum is big enough, it could quietly lose precision.)

Need Your Help

Rails nested form error_messages not displaying

ruby-on-rails validation

The whole code is from this question: Nested form validations not working in rails app

Writing tests for stochastic functions

python unit-testing testing random

I'm coding a package for experimenting with evolutionary algorithms, and needless to say, it includes a lot of stochastic methods. Now, I'd like to write some (doc)tests for this package, so I can ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.