Computing.Net > Forums > Unix > awk summing col1 for similar col2

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

awk summing col1 for similar col2

Reply to Message Icon

Name: samit04
Date: February 27, 2007 at 02:47:37 Pacific
OS: linux
CPU/Ram: dual rpocessor 2Gb ram
Product: HP workstation xw4100
Comment:

I have the following 2 cols in my file.

2 /url
5 /url1
3 /url
4 /url2
5 /url2

I want to sum up the col1 of simlar col2's and print it as 1 row. So the output of the above should be

5 /url
5 url1
9 /usr2

samit



Sponsored Link
Ads by Google

Response Number 1
Name: nails
Date: February 27, 2007 at 07:40:14 Pacific
Reply:

#!/bin/bash

sort -k 2,2 url.data|awk ' {
if(NR == 1)
{
f1=$1
f2=$2
continue
}

if(f2 == $2)
f1=f1+$1
else
{
print f1" "f2
f1=$1
f2=$2
}
}

END { print f1" "f2
} '


0

Response Number 2
Name: James Boothe
Date: February 27, 2007 at 16:46:07 Pacific
Reply:

And here's another approach. Rather than control-break logic, it just summarizes into an array. Both approaches have their advantages, depending on your data.

awk '{col2[$2]+=$1}
END {for(i in col2) printf "%5d %-8s\n",col2[i],i}' infile |
sort


0

Response Number 3
Name: samit04
Date: February 28, 2007 at 01:53:13 Pacific
Reply:

Thanks James. The power of associative arrays!!

samit


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Unix Forum Home


Sponsored links

Ads by Google


Results for: awk summing col1 for similar col2

Removing Duplicate Records www.computing.net/answers/unix/removing-duplicate-records/6375.html

awk to print last parameter www.computing.net/answers/unix/awk-to-print-last-parameter/6830.html

awk in shell script www.computing.net/answers/unix/awk-in-shell-script/6200.html