![]() |
Hello and Welcome from United States to the UNIX and Linux Forums! Thank You for Visiting and Joining Our Global Community.
|
|
google unix.com
|
|||||||
| Forums | Register | Forum Rules | Links | Albums | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
| UNIX for Dummies Questions & Answers If you're not sure where to post a UNIX or Linux question, post it here. All UNIX and Linux newbies welcome !! |
More UNIX and Linux Forum Topics You Might Find Helpful
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Columns to rows | mgirinath | Shell Programming and Scripting | 16 | 11-29-2007 07:03 PM |
| Cut rows | obedkhan | HP-UX | 2 | 08-23-2006 09:36 AM |
| Finding different rows | dombi | Shell Programming and Scripting | 2 | 03-06-2006 05:01 PM |
| Difference between two rows | JimJim | Shell Programming and Scripting | 7 | 07-05-2005 07:52 AM |
| Concatenate 2 rows into 1 row | indianadoug | Shell Programming and Scripting | 4 | 03-11-2005 11:05 AM |
![]() |
|
|
LinkBack | Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
||||
|
sum of all matching rows using awk
I have file
"1","x1897"," 89.10" "1","x2232"," -12.12" "1","x1897"," 389.10" "1","x2232"," 212.12" "1","x1897"," 19.10" "1","x2232"," 2.12" i want to add all 3 rd column rows (they have spaces also)for x1 and sum of 3rd column rows for x2 separately. I am very bad at awk. can some one help me ? |
|
||||
|
this is not homework problem..
this is what i did while read file do var=`echo $file | cut -f 3 -d "," | sed .... .... done < file but i donot wantt to use while loops ------------------- thanks for the replies. Will this work if the sum amount are in 13 th column or somewhere else ? I could not find them working... will this work if we need to find the sum on 13th field. File may contain around 30 fields sum2.awk { gsub(/\"| +/,"",$13) sum += $13 } END { print "Sum: ", sum; } $ awk -f sum2.awk file Last edited by i.scientist; 08-05-2008 at 11:57 PM.. |
|
||||
|
No, it wouldn't work, because awk does not know what character to use as a field separator, so it does not know what you mean when you refer to $13.
You can specify a regexp as a separator: Code:
awk -F '[",]+ *' '{ sum+=$14 } END { print "Sum: ",sum }' file
|
|
||||
|
Thanks,
this works fine if all the columns are included in " " In my case they are not. Sorry for not telling that. "1",,,,,"X1211","1", there may be empty fields seperated by commas. If so how to change the field seperator and how to obtain the sum of 13th column ? |
|
||||
|
awk -F '[,]' '{ gsub(/\"| +/,"",$13);sum+=$13 } END { printf "Sum: 0.2%d",sum }' file
this worked. Now can i get sum of only those rows matching X1 and X2 ? thanks for all your replies Last edited by i.scientist; 08-06-2008 at 10:55 AM.. |
![]() |
| Bookmarks |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|