The UNIX and Linux Forums  

Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
Google UNIX.COM


Shell Programming and Scripting Post questions about KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and OTHER shell scripts here.

Reply
 
Submit Tools LinkBack Thread Tools Search this Thread Display Modes
  #1  
Old 11-09-2007
Registered User
 

Join Date: May 2007
Posts: 104
AWK(?) Help

Hi all,

I'm having trouble figuring out awk. I'm pretty sure it would be the best tool for the job here. I have a tab-delimited file called score that looks like:
Code:
john     0         1         0
sam      0         1         1
john     2         1         1
sam     0         1          0
sam     1         1          1
john     2         1          1
There could be an unlimited # of names.

The columns are $1 = name, $2 = score, $3 = games, $4 = wins. I want to add up all of $2, $3 and $4 and also divide $4 by $3 (pct of games won) to produce a $5 for each unique name and display each name as it's own line (with the math done) and under a heading of NAME SCORE GAMES WINS PCT.

I'm able to print out the unique names with:
Code:
awk '{
arr[$1] = $1}
END {
for (x in arr )
print arr[x] }' score
However, I don't think that is very scalable to more names, and I'm not sure where the math of the associated columns needs to go.

Any help would be greatly appriciated.
Reply With Quote
Forum Sponsor
  #2  
Old 11-09-2007
Moderator
 

Join Date: Feb 2007
Posts: 2,329
Try this:

Code:
awk '
BEGIN {printf("NAME\tSCORE\tGAMES\tWINS\tPCT\n")}
{
  name[$1]=$1
  score[$1]+=$2
  games[$1]+=$3
  wins[$1]+=$4
}
END{for(i in name){printf("%s\t%s\t%s\t%s\t%f\n", name[i], score[i], games[i], wins[i], wins[i]/games[i])}}
' file
Regards

Last edited by Franklin52; 11-09-2007 at 03:07 PM. Reason: Forgot the last double quote
Reply With Quote
  #3  
Old 11-09-2007
Registered User
 

Join Date: May 2007
Posts: 104
Works like a charm... thank you... this taught me a lot about arrays, despite being for a dumb little shell script game

I really appreciate your help.
Reply With Quote
Google The UNIX and Linux Forums
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes




All times are GMT -7. The time now is 07:03 AM.


Powered by: vBulletin, Copyright ©2000 - 2006, Jelsoft Enterprises Limited.
The UNIX and Linux Forums Content Copyright ©1993-2008. All Rights Reserved.Ad Management by RedTyger Visit The Complex Event Processing Blog

Content Relevant URLs by vBSEO 3.2.0