Operating System - HP-UX
1826417 Members
3964 Online
109692 Solutions
New Discussion

BC to add items in a collumn

 
SOLVED
Go to solution
hpuxrox
Respected Contributor

BC to add items in a collumn

I have a file that looks like this,

143413413
412342346
432434877
434978867
432654657

How would I use bc to cat this file and add the numbers?
10 REPLIES 10
Peter Godron
Honored Contributor
hpuxrox
Respected Contributor

Re: BC to add items in a collumn

Sorry, I can not use awk or perl
Peter Godron
Honored Contributor

Re: BC to add items in a collumn

Hi,
found on an old website:
#!/bin/ksh
TOTAL=0
for NUMBER in `cat `
do
TOTAL=`echo $NUMBER + $TOTAL |bc -l`
done
echo $TOTAL
A. Clay Stephenson
Acclaimed Contributor

Re: BC to add items in a collumn

Here is one approach:

TF="/var/tmp/TF${$}"

trap 'eval rm -f ${TF}' 0 1 2 3 15

INFILE=myfile
echo "a=0" > ${TF}
cat ${INFILE} | while read N
do
echo "a+=${N}" >> ${TF}
done
echo "a" >> ${TF}
TOT=$(bc < ${TF})
echo "Total: ${TOT}"
If it ain't broke, I can fix that.
harry d brown jr
Honored Contributor
Solution

Re: BC to add items in a collumn

cat filename |xargs echo|sed "s/ / + /g"|bc

live free or die
harry
Live Free or Die
Peter Nikitka
Honored Contributor

Re: BC to add items in a collumn

Hi,

a solution with dc:

(sed '2,$s/$/+/' /tmp/num; print p) | dc

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"
Sandman!
Honored Contributor

Re: BC to add items in a collumn

Yet another way of doing the same thing...

# p=0; while read l;do p=$(echo "$l + $p" | bc); done < infile;echo $p

~cheers
Hein van den Heuvel
Honored Contributor

Re: BC to add items in a collumn

>> Sorry, I can not use awk or perl

Unacceptable.

Please explain.

Sure you can.

Apparently you can not use BC either, so why not use / learn somethign much more versatile and useful in the long run.

Regards,
Hein.
hpuxrox
Respected Contributor

Re: BC to add items in a collumn

.
Hein van den Heuvel
Honored Contributor

Re: BC to add items in a collumn

Randall,

You may not have liked my answer and that's ok, but please humor me and explain why it had to be 'bc' and why you had to 'cat' the file. I'm curious and always eager to learn!

Regards,
Hein.