Register
It is currently Tue Sep 23, 2014 10:20 am

read a file and add some integers


All times are UTC - 6 hours


Post new topic Reply to topic  [ 6 posts ] 
Author Message
 PostPosted: Sat Mar 06, 2010 12:26 pm   

Joined: Sat Mar 06, 2010 12:13 pm
Posts: 3
Hi,
I have a file (a.txt) with data in format :

100 Audi green
90 Audi yellow
30 Audi red
20 BMW red
2 BMW red
1 BMW yellow
80 Subaru white
60 Subaru black
..........
........


I want to make a script which add all the numbers and keep only the last colour.
For example

220 Audi red
23 BMW yellow
140 Subaru black


Could you help me do it ??


220 red


Top
 Profile  
 PostPosted: Sat Mar 06, 2010 1:43 pm   
User avatar

Joined: Sat Jun 13, 2009 8:53 pm
Posts: 73
Location: Texas!
awk is just the tool for this.

Here's a source file (foo.awk):
Code:
{number[$2] += $1; names[$2] = $2; color[$2] = $3}

END {for (name in names) print(number[name],name,color[name])}


And here is how you call it:
Code:
awk -f foo.awk a.txt


- thobbs


Top
 Profile  
 PostPosted: Sat Mar 06, 2010 2:04 pm   

Joined: Sat Mar 06, 2010 12:13 pm
Posts: 3
thanks a lot for your help.

But I have to do it in one file, so I made a function like :

Code:
fun(){
number[$2] += $1;
names[$2] = $2;
color[$2] = $3;

for name in names;do
  print(number[name],name,color[name])
done
}


and call it :
Code:
fun "a.txt"


Something I am doing wrong and does not run.


Top
 Profile  
 PostPosted: Sat Mar 06, 2010 3:46 pm   
User avatar

Joined: Sat Jun 13, 2009 8:53 pm
Posts: 73
Location: Texas!
Well, I suppose if you want it all in one file (foo.sh), just do this...
Code:
#!/bin/bash
awk '{number[$2] += $1; names[$2] = $2; color[$2] = $3} END {for (name in names) print(number[name],name,color[name])}' $1


Then you can just call:
Code:
./foo.sh a.txt


Is that what you were asking? Your code example from the last post looks like it's trying to use awk syntax in a bash script.

- thobbs


Top
 Profile  
 PostPosted: Sat Mar 06, 2010 3:56 pm   

Joined: Sat Mar 06, 2010 12:13 pm
Posts: 3
thanks a lot !
It works perfect


Top
 Profile  
 PostPosted: Sat Mar 06, 2010 5:31 pm   
User avatar

Joined: Sat Jun 13, 2009 8:53 pm
Posts: 73
Location: Texas!
Sure, no problem!

- thobbs


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 6 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: Bing [Bot] and 5 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP