Operating System - HP-UX
1831985 Members
3792 Online
110034 Solutions
New Discussion

Adding a column of numbers in a file

 
SOLVED
Go to solution
Paddy O'Connell
Frequent Advisor

Adding a column of numbers in a file

Hi,

I'm looking to total up all the numbers in a file as part of a shell script.

sample file is like below, now i'll have hundreds of numbers

68
8
2
2

Thanks
Paddy
4 REPLIES 4
Peter Godron
Honored Contributor
Solution

Re: Adding a column of numbers in a file

Paddy,
you don't mention a preference for solution, so here is one in awk:
awk 'BEGIN {total=0;} {total=total+$1;} END {print total,"\n";}' data.lis

Please also read:
http://forums1.itrc.hp.com/service/forums/helptips.do?#33 on how to reward any useful answers given to your questions.
Paddy O'Connell
Frequent Advisor

Re: Adding a column of numbers in a file

Thanks Peter for quick response i'll try it.

As part of the same script all these numbers are generated into a file. I want to total the number in them and if it's above a certain treshold it will mail me.

So will i cat the file with all numbers in it and pipe it to your awk command you supplied?

Paddy
Paddy O'Connell
Frequent Advisor

Re: Adding a column of numbers in a file

It's ok Peter, i removed the data.lis you put at the end and it's set to cat the file and pipe to awk.
Thanks for that

Paddy
Peter Godron
Honored Contributor

Re: Adding a column of numbers in a file

Paddy,
my test was:
$ cat a.lis
1.1
2.5
3
4
$ level=`awk 'BEGIN {total=0;} {total=total+$1;} END {print total,"\n";}' a.lis`
$ echo $level
10.6
$
Just to check that it worked with float as well.

In your case you can use the $level bit to then decide whether to mail. Something like:

level=`awk ....
if [ $level -gt 75 ]
then
echo "Level is $level" | mailx -s "level reached" usr@aol.com
fi