I'd like to sum up numbers in a plain text file. Is there somehow I can do this with a command or a bash script?

Say I want to extract the number in a pattern that looks like this:

… text text …
Removed 50 items out of 50 items.
… text text …
Removed 34 items out of 50 items.
… text text …

So in the case above, I'd like to extract the first number in the lines that they pop up and sum it up. In the example the result should be 84. I know how to grep it, but that's the extent of my knowledge of *nix commands.

  • 4
    Grep to filter for the lines, cut to isolate the numbers, awk to sum up numbers. – Daniel Beck Jun 27 '11 at 11:42
  • awk can duplicate the functionality of grep and cut, so why not just use awk alone? – Stephanie Jul 11 '11 at 2:13


  grep Removed filename | awk '{sum += $2} END { print "sum=", sum }'


 awk '/Removed/ { sum += $2 } END { print "sum=", sum }' filename
  • end -> END or else nothing will output. Don't think the version of awk I'm using (in Cygwin) can use lowercase end. – Spoike Jun 27 '11 at 13:22
  • But other than that, it works. :) Thanks. – Spoike Jun 27 '11 at 13:33

with perl you would write this:

perl -a -n -e '$sum += $F[1] if $F[0] eq "Removed"; END { print $sum }'  filename(s)

Where -a mean autosplit on spaces into the @F array $F[0] is the first element where the word Removed should be and $F[1] is the second element.

-n means go over the files given on the command line, line by line

-e means, take the next string as the script (instead of a file)

If you are running on native windows (I see from the comment mentioning Cygwin) then you could use the "Padre on Strawberry" package for all this though due to the different shells you would switch the ' and " characters.

  • 1
    +1. Alternative perl -ane '/Removed/ and $sum += $F[1]; END { print "$sum\n" }' filename – RedGrittyBrick Jun 27 '11 at 13:56
  • Indeed. That was my first solution but I wanted to avoid using two concepts there. – szabgab Jun 27 '11 at 14:03

Sometimes I want to sum up multiple columns that appear in a file. This script sums up columns that "look numeric"

#!/usr/bin/perl -w
# csum
# Sum up numerical fields in a text file

my $i;
my @sum;

while (<>)
    my @F = split;
    for $i (0..$#F)
        if ($F[$i] =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/)
            $sum[$i] += $F[$i];

print "-" x 75 . "\n";
print join "\t", map {$_ or ""} @sum;
print "\n";
if [ $# -ne 1 ]
    echo "Usage: $0   number"
    echo "       I will find sum of all digit for given number"
    echo "       For eg. $0 123, I will print 6 as sum of all digit (1+2+3)"
    exit 1

while [ $n -gt 0 ]
    sd=`expr $n % 10`
    sum=`expr $sum + $sd`
    n=`expr $n / 10`
    echo  "Sum of digit for numner is $sum"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.