how do you to add numbers incrementally?

I've refined the filesystem size using awk and directed to a file name.

eg, here's the content in a file called "numbers"

$cat numbers
345
543
23423456
44435
546
.
.

how do you write a script to all these numbers to get the total?

thanks a lot.

sum=0
for i in `cat numbers`
do
((sum=sum+$i))
done

echo "sum=$sum"

bhargav,
thanks for a quick response. that did it.

Also possible in awk...

awk '{m+=$1}END{print m}' numbers

Hi there,

does someone knows about such a simple method to add hexadecimal numbers using awk ?

thanks,
homefp

To sum two numbers....

With GNU awk, yes

$ awk 'BEGIN { printf "%x\n", 0xa + 0x2 }'
c

Prefix your hexadecimal values with 0x (or 0X), and use %x as a format specifier.

You also could use ksh

$ var_a="16#a"
$ var_b="16#2"
$ typeset -i16 var_c
$ ((var_c=var_a+var_b))
$ echo $var_c
16#c

Which is what you'd expect in base 16 (A + 2 = C).

thanks,

how then would I replace the following :

awk '{m+=$1}END{print m}' numbers

with hexa numbers in $1 field ?

I need to have it as simple as possible in a shell script.

I actually prepared a script that does the job, but then re-read the tone of your post. "I need to have it as simple as possible in a shell script." sounds a little bit too much like a homework demand.

If it isn't homework, then try to write the script yourself, and then post what you've done so far - and tell us where/why it isn't working. The pointers I gave for using the Korn shell should be enough to allow you to write your script.

Cheers
ZB

Really sorry ZB, I didn't mean it...

My concern is that I don't know how to initialize the variables (typeset...with awk).
Ciao.

here is my own solution :

result=`cat $filein | awk '{print $3}' | sed s/0x//g | tr [a-z][A-Z]`
result=`echo "obase=10;ibase=16;$result" | bc | awk '{bytes = bytes + $1} END {print bytes}' `
echo "Result = $result"

More simpler way should be possible.
Thanks anyway ! :slight_smile:

Homefp