Grouping and Calculating

Hi All,

I want to read the input file and store the output in the Output file. I pasted the sample Input and Output file below. Help me with this.

Input file

ITEM1	AAAAA	1
ITEM1	BBBBB	1
ITEM1	CCCCC	1
ITEM2	AAAAA	5
ITEM2	CCCCC	4

==================================

Output File

ITEM1	AAAAA	1
		BBBBB	1
		CCCCC	1
ITEM1	TOTAL	3

ITEM2	AAAAA	5
		CCCCC	4
TTEM2	TOTAL	9

		TOTAL	12

==================================

Hi, if the items are grouped like in your sample, try something like:

awk '
  function pr(i) {
    printf "%s", i A
    print  i, "TOTAL", T
  }
  {
    if(i!=$1 && NR>1) pr(i)
    i=$1
    $1=x
    A=A $0 ORS
    T+=$3
    GT+=$3
  }
  END {
    pr(i)
    print "", "TOTAL", GT}
' OFS='\t' file

Otherwise, try something like this:

awk '
  {
    i=$1;
    $1=x
    A=A $0 ORS
    T+=$3
    GT+=$3
  } 
  END {
    for(i in A) {
      printf "%s",i A
      print  i, "TOTAL", T
    }
    print "", "TOTAL", GT
  }
' OFS='\t' file

But then the items will not necessarily appear in the order of the input file