1755126 Members
3389 Online
108830 Solutions
New Discussion юеВ

Awk sum script

 
Eugene Matusovsky
Occasional Contributor

Awk sum script

I have text file

1
2
3

I would like to use awk to sum up the total of these numbers and output the number 6.

Is this possible in awk?
7 REPLIES 7
R.K. #
Honored Contributor

Re: Awk sum script

Hi Eugene,

# cat a1
1
2
3

# awk 'BEGIN {sum=0}{sum+=$1} END {print sum}' < a1
6

Hope this helps..!
Don't fix what ain't broke
Kapil Jha
Honored Contributor

Re: Awk sum script

awk '{ s += $1 } END { print "sum: ", s }' abc

abc is file name.

BR,
Kapil+
I am in this small bowl, I wane see the real world......
Dennis Handly
Acclaimed Contributor

Re: Awk sum script

>I would like to use awk to sum

awk(1) has an example that does that.
Eugene Matusovsky
Occasional Contributor

Re: Awk sum script

This all great! Thanks so much for everyone's help. I'm also considering doing the sum in ksh/bash only...Is this possible?

Thank You
OldSchool
Honored Contributor

Re: Awk sum script

sure...for integer math

typeset i sum
typeset i incr

sum=0
echo $sum

while read incr;
do

let sum=$sum+$incr
echo $sum
done < yourfile


there are also methods involving bc that will do reals/floats
Dennis Handly
Acclaimed Contributor

Re: Awk sum script

>OldSchool: let sum=$sum+$incr

You may want to just use:
(( sum += incr ))
James R. Ferguson
Acclaimed Contributor

Re: Awk sum script

Hi:

> Thanks so much for everyone's help. I'm also considering doing the sum in ksh/bash only...Is this possible?

Yes, as OldSchool showed you, the shell can do this. Beware that in HP-UX, the Posix ('/usr/bin/sh') shell limits you to 32-bit arithmetic. If you are running 11.23 or later, the Korn shell ('/usr/bin/ksh') will support 64-bit arithmetic.

Running OldSchool's code and adding the numbers found in an input file:

1
2147483648
2
3

...yields:

-2147483642

Changing to a Korn shell yields the correct value:

2147483654


Also:

typeset i sum

...should be:

typeset -i sum

Regards!

...JRF...