shell script add each row value

Hi,

I wrote below small script which will add up each row value from a file and print the total, but it is not.plz let me know what is wrong.script hangs and not displaying anything.
-----------------
while read line ; do
sum=0;
sum=$sum+$line;
done
echo $sum;
exit 0;
------------------
file has below rows:
37.17
65.53
106.14
45.12

The first thing I notice offhand is that you zero out the sum inside the while loop for every line.

But also, you don't display how you are getting the contents of the file to be read in the while loop. Can you show what you did there. If nothing, than that is the reason the script is "hanging". It's reading stdin which means it's awaiting your input.

Then there is the problem that you are working with floating point numbers. Does your shell handle that? Mine doesn't

Hi,

I have modified the script:

FILE=/tmp/cc
SUM=0;
cat $$FILE | while reaad line; do
SUM=$SUM+$LINE;
done
echo $SUM;
exit 0;

but when I runn the script, it says "./cc.sh[6]: 0+38.08: not found"

You have solved a few problems. You've got the file contents going into the While loop so that's good, (I'm assuming the double $$ before FILE is just a typo, if not get rid of one '$' there).

You're not zeroing out the sum, IN the while loop. Also good.

But that leaves us with the fact that your still dealing with floating point numbers, not integers.

Do a 'man' on your shell and see if it supports 'typeset -E' or 'typeset -F'. If so, try using:

typeset -F SUM
typeset -F LINE

before you set SUM=0

the easiest way:

#!/bin/ksh
echo $(sed -e 's/$/+/' /tmp/cc) 0 | bc

Hi,

I tried this, got it while search.

awk '{sum += $1} END {printf "%.2f\n", sum}' file..it gave the ans, but do not know if it correct..

vgersh99, can you explain the command?is this a oneline command for adding the values in rows in file?

rwuerth, I put the typeset in script,

But it gaves the same error, but decimal numbers are missing in error.

You will have to add it up manually to verify the correct answer, but if you're just using the numbers you gave us above as a test file, the answer would be 253.96.

If using typeset -F or typeset -E isn't working it's probably not supported.

vgresh99's response is perfect actually. You could wrap that up in a command substition to put the value into a variable for use elsewhere if needed.

we convert all 'new line' ($) characters to '+' in reality 'flattening' the file like so:

1
2
3

becomes

1+2+3+

You notice a 'trailing' '+'? That's last new line. So we suffix the result with '0' - adding '0' to the final. So in our example it becomes:

1+2+3+0

We pipe the result (using 'echo') into 'bc' to perform the actual math.

yes -trying it would help answering the question

vgersh99, rwuerth

awk '{sum += $1} END {printf "%.2f\n", sum}' file
-----
echo $(sed -e 's/$/+/' /tmp/cc) 0 | bc

Both command works.

thank you for your help.