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

Matching columns + sum 1

Status
Not open for further replies.

nabana2

Technical User
Sep 26, 2005
21
ZA
hi

I am new to awk and am struggling with arrays. I am not sure how to print whole rows from matching columns or
perform an action on the results. For example from this data :

12a 3010 a 0919 10
12a 3510 a 0919 20
12a 3510 s 0919 40
12a 3520 a 0919 10
12a 3525 a 0919 20
12a 3525 s 0919 50
12a 9917 a 0919 10
12a 6548 a 0919 10
12a 6548 s 0919 30
12a 6548 s 0919 20

I want to match columns 1, 2 and 4 and sum column 5
for the matching results. leaving me with:

12a 3010 a 0919 10
12a 3510 a 0919 60
12a 3520 a 0919 10
12a 3552 a 0919 70
12a 9917 a 0919 10
12a 6548 a 0919 60

If anyone could show me how this is done i would be very
gratefull. Verbose steps would be a bonus.

 
how did you exactly come up with this given your sample input: ?
Code:
12a    3510    a   0919    60

how do you know what value to put in the 3-rd column in this example?

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
nawk -f naba.awk myFile.txt

naba.awk:
Code:
BEGIN {
  OFS=SUBSEP="\t"
}
{
  _idx=$1 SUBSEP $2 SUBSEP $4
  if ( !(_idx in arr3rd) ) arr3rd[_idx]=$3
  arr[$1, $2, arr3rd[_idx], $4] += $5
}
END {
  for( i in arr )
    print i, arr[i]
}

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Thanks vlad

Just been running it on real data.
Works perfectly, no changes.
Third column not too important at the moment,
was just trying to simulate the real data as
closely as possible.

Trying to understand the code at the moment.

Thanks again
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top