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?

Answers


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

(Note the complete lack of error checking.)

EDIT :

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

BEGIN {
    ok = 1
}

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

END {
    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

How to remove trailing whitespaces with sed?

sed whitespace

I have a simple shell script that removes trailing whitespace from a file. Is there any way to make this script more compact (without creating a temporary file)?

Stopping a thread in a Tomcat Application - which method?

java multithreading apache tomcat

I'm using the below implementation to stop a thread in Tomcat. The code works, but I'm wondering two things: