Operating System - HP-UX
1833883 Members
1731 Online
110063 Solutions
New Discussion

Re: A quick on scripting ? Multiple addition. help!

 
SOLVED
Go to solution
rveri
Super Advisor

A quick on scripting ? Multiple addition. help!

How do I add this values from the file . Any script can help me.

datafile.txt
#---------------
1.78
9.00
8.80
128.82
7.13
0.71
19.49
5.34
4.61
7.94
3.23
47.82
190.03
6.72
16.28
0.06
16.45
0.41
1.17
5.82
5:38
41.53
---------------

How to use bc or any other utility , to add this values altogether.

Thank you.
7 REPLIES 7
Peter Godron
Honored Contributor
Solution

Re: A quick on scripting ? Multiple addition. help!

cat datafile.txt | awk '{sum=sum+$1} END {print sum}'
Steve Steel
Honored Contributor

Re: A quick on scripting ? Multiple addition. help!

Hi

file=$1
let start=0
cat $file|while read line
do
if [ "$start" = "0" ]
then
start=$line
else
start1=$(echo $start + $line |bc)
echo $start + $line = $start1
start=$start1
fi
done
~

Steve Steel
If you want truly to understand something, try to change it. (Kurt Lewin)
rveri
Super Advisor

Re: A quick on scripting ? Multiple addition. help!

Peter , excellent!!
It works great.



# cat datafile.txt | awk '{sum=sum+$1} END {print sum}'
528.14
---------------

Thanks all who replied.
harry d brown jr
Honored Contributor

Re: A quick on scripting ? Multiple addition. help!

If you fix the second to last line from 5:38 to 5.38, then this would also work:

cat datafile.txt|xargs echo|sed "s/ / + /g"|bc

live free or die
harry d brown jr
Live Free or Die
Arturo Galbiati
Esteemed Contributor

Re: A quick on scripting ? Multiple addition. help!

Hi,
It's not necessary to use cat:
awk '{t+=$1};END {printf "%10d\n", t}' datafile.txt

I also suggest to use printf instead of print to print formatted result in a readable way.

HTH,
Art
rveri
Super Advisor

Re: A quick on scripting ? Multiple addition. help!

Hi Arturo ,

good command thanks, but its not giving the decimal values.

# awk '{t+=$1};END {printf "%10d\n", t}' datafile.txt

528
#
-------------
The actual result is 528.14


Thanks.
James R. Ferguson
Acclaimed Contributor

Re: A quick on scripting ? Multiple addition. help!

Hi Revi:

'printf' has many formatting options. To sum the contents of your file and retain 2-decimal places:

# awk '{t+=$1};END {printf "%10.2f\n", t}' file

See the manpages for 'printf' for more information.

Regards!

...JRF...