awk script Equivalent .

Hello. I wrote some code for an awk command but I want to learn to turn it into an awk script but am stuck. I have a file (data.csv) that has the following data:

ADD,1,3,5,8,10,11,54
SUB,1,2,3,4
ADD,15,18,21,42,37
ADD,1,1,1,0,0,3,16
ADD,4,1,8,0,4,6,13,16,17,20,8,6,4
SUB,13,8

If the line has ADD, I added. Subtract for lines that start with SUB. I am then to return the sum of all the lines. This is the awk code that I have:

awk -F',' '{if($1 == "ADD") {for(i=2;i<=NF;i++) t+=$i; print t;} else { t=$2;for(i=3;i<=NF;i++) t-=$i;print t; }t=0}' data.csv

The only issue with the output is that it provides a sum for each line but not the total sum. So how would I turn this into a script?

How does a script differ from what you have above?
How does a sum per line differ from a total across all lines?

Print a total in the END section:

awk -F',' '/^ADD/ {F=1} /^SUB/ {F=-1} {for (i=2; i<=NF; i++) {S+=$i*F; t+=$i*F}; print S; S=0} END {print t}' file
92
-10
133
22
107
-21
323

It doesn't. I just wanted to learn how to put it in a cleaner format (script) like:

BEGIN {


}


{


}


END {


}

That's a matter of logics, style, and personal taste. Use consistent indentation, keep blocks together, try to find some meaningful nomenclature for variables and functions.

awk -F',' '
/^ADD/  {F = 1
        }
/^SUB/  {F = -1
        }
        {for (i=2; i<=NF; i++) S += $i*F
         print S
         t += S
         S = 0
        }
END     {print t
        }
' file
1 Like

So if I want to turn that line of code into the format I had mentioned:

BEGIN {   }   {   }   END {   }

Am I even in the ballpark with the following?

begin{
IFS=","
}

{
t=0;
if ($1 == "ADD"){
        for (a=2; a <= NF; a++)
                b += $a;
        else {
                b=$2;
                for (a=3; a <= NF; a++)
                        b=$a)
}
}

end {
printf ("The Sum is: ", b)

}

I corrected and formatted your code to give you an idea how it could be formatted:

BEGIN {
  FS=","
}

{
  if ($1 == "ADD") {
    for (a=2; a <= NF; a++)
      b += $a
  }
  else if ($1 == "SUB") {
    for (a=2; a <= NF; a++)
      b -= $a
  }
}

END {
  printf ("The Sum is: %s\n", b)
}

You would need to call it like this:

awk -f awkscript infile