Re: Can someone help me out of this?
- From: Ed Morton <morton@xxxxxxxxxxxxxx>
- Date: Tue, 07 Feb 2006 14:53:14 -0600
RK wrote:
> Hi, just do not know what happens to this.
>
> I have a merge case here, something like the following sorted text.txt
>
> AB,BC,3,
> AB,BC,4,
> CD,CA,5,
> CD,CD,4,
>
> I got to merge the same f1 and f2, and sum up f3 to make one line
> entry. If different, then put the original line there.
>
> Then I made an awk1 like this:
> ==================
> #!/bin/awk -f
> BEGIN{FS=",";}
> NR==1 {
> f1 = $1 ;
> f2 = $2 ;
> sm = $3 ;
> }
>
> NR>1 && $1==f1 && $2==f2 {
> sm += $3 ;
> }
>
> NR>1 && ($1!=f1 || $2!=f2) {
> printf("%s,%s,%d,\n",f1,f2,sm);
> f1 = $1 ;
> f2 = $2 ;
> sm = $3 ;
> }
>
> END{
> printf("%s,%s,%d,\n",f1,f2,sm);
> }
> ============
>
> awk1.awk text.txt
> It works:
>
> AB,BC,7,
> CD,CA,5,
> CD,CD,4,
>
>
> But if I made it as awk2 like
>
> ==============
> #!/bin/awk -f
> BEGIN{FS=",";}
> NR==1 {
> f1 = $1 ;
> f2 = $2 ;
> sm = $3 ;
> }
>
> NR>1 && ($1!=f1 || $2!=f2) {
> printf("%s,%s,%d,\n",f1,f2,sm);
> f1 = $1 ;
> f2 = $2 ;
> sm = $3 ;
> }
>
> NR>1 && $1==f1 && $2==f2 {
> sm += $3 ;
> }
>
> END {
> printf("%s,%s,%d,\n",f1,f2,sm);
> }
> =============
>
> It works a wrong way:
>
> awk2 text.txt
>
> AB,BC,7,
> CD,CA,10,
> CD,CD,8,
>
> How could the two different positioning of the condition clauses make
> it work or not in AWK?
You're summing and resetting based on those conditions. In one case you print and reset before the sum, in the other you do it afterwards.
I know you have a version that works, but try this as it's a bit more consise and robust:
awk 'BEGIN{FS=OFS=","}
{key = $1 OFS $2}
key != prev {if (prev) print prev,sm; sm=0}
{sm += $3; prev = key}
END{print prev,sm}' file
Regards,
Ed.
.
- Follow-Ups:
- Re: Can someone help me out of this?
- From: RK
- Re: Can someone help me out of this?
- References:
- Can someone help me out of this?
- From: RK
- Can someone help me out of this?
- Prev by Date: Re: Testing for a pattern in a file
- Next by Date: chown cmd
- Previous by thread: Can someone help me out of this?
- Next by thread: Re: Can someone help me out of this?
- Index(es):
Relevant Pages
|