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

Using awk to add columns until account number changes... 1

Status
Not open for further replies.

zag

Programmer
Mar 14, 2000
19
0
0
GB
Hi all you awk whizzos., wonder if you can help me out here, I would appreciate it immensely!
Here is a sample of my file:

12345678 23
12345678 10
33333333 1
444444444 3
444444444 6

Left column is the account number, right column is number of books.

What I am trying to do is get awk to add each account number's 2nd field together, then print the account number and total for each, i.e.

12345678 33
33333333 1
444444444 9

I have tried using the following shell script but as you can imagine, with a large(ish) file (13000 odd lines) it takes forever!!

for acct in `cut -f1 -d ' ' sort.txt|sort -u`
do
acct_total=0
set `cat sort.txt | grep $acct |cut -c12-`

while [ $# -gt 0 ]
do
acct_total=`expr $acct_total + $1`
shift 1
done

echo $acct $acct_total >> blob.txt
done

I thought I knew a little bit about awk but this one has me stumped!
 
This should do it.

{
if (NR > 1 && savacct != $1) {
print savacct " " tot
tot = 0
}
savacct = $1
tot += $2
}
END {
print savacct " " tot
}

Hope this helps.

CaKiwi
 
Hi Cakiwi,
Many thanks for your script example. It worked perfectly and at lightening speed, as is always impressive with awk.
Could you enlighten me on a couple of syntaxy type things though, pls... i.e. NR > 1
(I thought NR started at 0 at input?)

and how come we need to print after END i.e.

END {
print savacct " " tot

...haven't we already processed the last record?
 
Hi Zag,

NR starts at 1 for the first input record so the if statement prevents us from printing out the account number and total before we have processed any records. We need the END because when we reach the end of the file we have been adding up the total for the last account number but have not yet printed it out.

Hope this is clear

CaKiwi
 
Clear as daylight., seems obvious now!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top