Re: Can someone help me out of this?





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.


.



Relevant Pages

  • Re: Can someone help me out of this?
    ... I got to merge the same f1 and f2, and sum up f3 to make one line ... But if I made it as awk2 like ... How could the two different positioning of the condition clauses make ... it work or not in AWK? ...
    (comp.unix.shell)
  • Can someone help me out of this?
    ... I got to merge the same f1 and f2, and sum up f3 to make one line ... But if I made it as awk2 like ... How could the two different positioning of the condition clauses make ... it work or not in AWK? ...
    (comp.unix.shell)
  • Re: Can someone help me out of this?
    ... > But if I made it as awk2 like ... consise and robust: ... way AWK1 should do. ... simple awk condition can do no matter where you put it between BEGIN ...
    (comp.unix.shell)