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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

adding numbers in a file 3

Status
Not open for further replies.

chanman525

IS-IT--Management
Oct 7, 2003
169
US
Hey all. I've got a file that looks like the following:

81011, prt8, 0
81006, prt8, 28085
81009, prt8, 925
81011, prt8, 0
81006, prt8, 28085
81009, prt8, 925

All I want to do is add the numbers in the third column. Right now I've got...

cat test | read a1 a2 a3
sum $a3

but it's just saying that 0 cannot be found. Am I going about this the right way?

Thanks for any help you can give.
 
I know that can be done easily by awk!

I will test it and come back to you

Regards,
Khalid
 
not awk (my awk-fu is weak), but a ksh solution:

Code:
total=0
while read -r a1 a2 a3
do
read a1 a2 a3
(( total=total+$a3 ))
done < numbers.txt
echo "total = $total"

 
That's how i did it

Code:
cnt=0
for i in `awk '{print $3}' readnums`
do
((cnt=cnt + i))
done
echo $cnt

I know its not the perfect way of using awk any way :)

But it works :)

Regards,
Khalid
 
Eeek. Just looked over my solution - The read after the "do" statement - it doesnt belong, remove it.
 
I didn't think so, but I don't question you AIX guru's.

Thanks for the help from both of you. Not sure which one I'll go with, but they both work great.

Thanks again guys.
 
awk '{sum+=$3} END{print sum}' /path/to/file


HTH,

p5wizard
 
This is just plain stuff. Y'all should check out some of the code examples the real gurus over at the AWK forum forum271 dish out...

p5
 
Oh yeah that's what i was trying to do :p

Thanks p5wizard

Regards,
Khalid
 
awk '/.*/ {
total_count=total_count+$3
}
\END {
print total_count
}' /filename

should do the trick

Dave
 
oops... missed a tidier awk solution a cpl of posts earlier
 
And heres a nice little tutorial to expand your knowledge.


Mike

"Whenever I dwell for any length of time on my own shortcomings, they gradually begin to seem mild, harmless, rather engaging little things, not at all like the staring defects in other people's characters."
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top