Operating System - HP-UX
1834417 Members
1683 Online
110067 Solutions
New Discussion

Addition of numerical entries within a file

 
SOLVED
Go to solution
Craig Basham
Occasional Contributor

Addition of numerical entries within a file

For simplicity sake, imagine a file with a number of entries all on seperate lines. Each entry is a number. Is there a way of performing and addition function on all of these entries.

Eg.

File contents:

23
45
34
22
3

What command will tell me that the total of these numbers in this file is 127 ?
5 REPLIES 5
Stefan Farrelly
Honored Contributor
Solution

Re: Addition of numerical entries within a file


Indeed there is;

eg. your input file is called /tmp/tt

let X=0
for i in $(cat /tmp/tt)
do
let X=$X+$i
done
echo $X

This will display the total.
Im from Palmerston North, New Zealand, but somehow ended up in London...
Andreas Voss
Honored Contributor

Re: Addition of numerical entries within a file

Hi,

here the awk solution:

awk '{sum+=$1}END{print sum}'

Regards
federico_3
Honored Contributor

Re: Addition of numerical entries within a file


cat file | awk 'TOT==41 END {print TOT} '


federico_3
Honored Contributor

Re: Addition of numerical entries within a file


cat file | awk 'TOT+=$1 END {print TOT} '


Craig Basham
Occasional Contributor

Re: Addition of numerical entries within a file

Cheers guys!