Operating System - HP-UX
1827243 Members
2385 Online
109716 Solutions
New Discussion

Re: Adding multiple lines up and getting a total

 
SOLVED
Go to solution
Warren griggs
Frequent Advisor

Adding multiple lines up and getting a total

Hi,

I have a file that looks like this...

45
34
23

What I need to do is add each line up to get a total.

ie for the example above ...

45+34+23 Total = 102

I think I need to use awk for this but cannot remember how.

Any help would be great.

Thanks,
Colin.
7 REPLIES 7
Geoff Wild
Honored Contributor
Solution

Re: Adding multiple lines up and getting a total

Try this:

awk 'BEGIN {total=0;} {total=total+$1;} END {print total,"\n";}'

Rgds...Geoff
Proverbs 3:5,6 Trust in the Lord with all your heart and lean not on your own understanding; in all your ways acknowledge him, and he will make all your paths straight.
Patrick Wallek
Honored Contributor

Re: Adding multiple lines up and getting a total

If the file just contains the single value you could do:

#!/usr/bin/sh

TOTAL=0
for i in $(cat file)
do
let TOTAL=$TOTAL+$i
done

echo "The total is $TOTAL"
Jarle Bjorgeengen
Trusted Contributor

Re: Adding multiple lines up and getting a total

awk 'BEGIN {total=0} {total=total+$NF} END {print "Total is : " total} ' filename

Rgds Jarle
Robin Wakefield
Honored Contributor

Re: Adding multiple lines up and getting a total

...or...

perl -lne '{$t+=$_}END{print $t}' filename

rgds, Robin
Jean-Louis Phelix
Honored Contributor

Re: Adding multiple lines up and getting a total

Perhaps you will like this one ...

echo $(($(cat file | tr '\012' '+')0))

Regards.
It works for me (© Bill McNAMARA ...)
Chris Vail
Honored Contributor

Re: Adding multiple lines up and getting a total

In Unix, there's always several different ways to do any one thing. You've already got some good ones, here's another:
#!/bin/ksh
for AMOUNT in `cat $FILE`
do
(( TOTAL = "$TOTAL" + "$AMOUNT" ))
done
echo $TOTAL

Chris
John Meissner
Esteemed Contributor

Re: Adding multiple lines up and getting a total

or yet another way....

number=$(cat file)
e=0
for i in $number
do
((e=e+$i))
done
echo $e

now if you have multiple columns in your file you can just change the value to $number to assign the field you wish to add up.

i.e.
number=$(cat file | awk '{print $2}')

and the 2nd field would be added

All paths lead to destiny