For loop problem extracting data

I have a problem with my loops. I have a file called users.dat, it has all the users in it. Then I extracted a list of users sending out number of mails with date from Netscape logs. The extracted list (mailuse.dat) has 3 fields: username, number of mails, date. (One user can show up several times). I would like to add up all the numbers in the 2nd field. Here is my lame effort:
--first loop gets users, second loop tries to get the 2nd field and adds them up.---

for i in `cat users.dat | awk '{print $2}'
total=0 
do
  for j in `grep $i mailuse.dat | awk '{sum+=$2}'
  do
  total=`expr $total + $j`
  echo $total, $j
  done
done

-----------
TIA, (plese help!)
Nitin :slight_smile:

added code tags for readability --oombera

The users.dat file serves no useful purpose and it is leading you into a double loop. Try this...

#! /usr/bin/ksh

firsttime=1

sort mailuse.dat | while read user count date ; do
        if ((firsttime)) ; then
                firsttime=0
                olduser=$user
                sum=0
        fi

        if [[ $user != $olduser ]] ; then
                echo $olduser $sum
                olduser=$user
                sum=0
        fi
        ((sum=sum+count))

done

echo $olduser $sum

exit 0

Perderabo,
Thanks a million! Your script is fast, it doesn't grep each name in the user.dat thingy.

I also tried this thing, thought I would just paste it. (I do realize that this is very bad programming and slow too!)

#!/bin/sh
rm /tmp/mails.log  # remove old logs
for i in `cat walusers.dat | awk '{print $1}'`
do
 total=0;
 echo $i; # shows which users have gone by!!
 for j in `grep $i maildeli.final | awk '{print $2}'`
  do 
  echo $j;
  total=$total+$j;
  done;
 echo $i " " $total >>/tmp/mails.log;
done

After using Perderabo's script, I decided to join the script output with users.dat. That gave me a a list of "power mail users".
-----
join -a 1 -o Nomails -e 1.1 2.2 user.dat mails.log >usage.list
-----
Thanks again! :smiley:

added code tags for readability --oombera