Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Math Adding

Status
Not open for further replies.

jestrada101

Technical User
Mar 28, 2003
332
How can I add data?

---data----
TEAMA 100
TEAMB 200
TEAMC 300
-----------

how can I read this data in and add to get a total of 600?

Thanks
JE
 
Awk can do tbis quite easily
Code:
awk '{ sum += $2 }
END { print sum }' data

data being the name of your data file with numbers in field 2

--
 
Thanks...
if one has a variable with data stored in it.. how can one read it in to add...

for example..
we have teh file data again...

RESULTS=`cat data`

then there is column 2 in data that I need to add... is this possible?
 
RESULTS=`cat data`
But this removes all the newlines from the file and leaves you with a single line containing
Code:
TEAMA 100 TEAMB 200 TEAMC 300

Sure you could do something, but it seems to be adding a layer of difficulty over my first answer.

--
 
In ksh, provided your data file have less than 512 lines, you can try something like this:
Code:
set -A arr $RESULTS
typeset -i i=0 tot=0
while [ $i -lt ${#arr[*]} ]; do
  tot=$((tot+${arr[$((i+1))]}))
  i=$((i+2))
done
echo $tot

Hope This Help
PH.
 
Use salems instructions but encapsulate and print
the command to store the value in a shell variable.
Code:
sum=`awk '{sum += $2 } END {print sum}'`
echo $sum
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top