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

Sum per Header 3

Status
Not open for further replies.

namaycushs

Technical User
Aug 10, 2004
7
0
0
CH
Hi,

I want to build the total for each header.
Output of a command looks like this:

Header: A

Type Length
X 10
X 5
X 15
Y 2
Y 5
Y 1
Header: B
X 4
X 10
Y 3
Y 1


Now, I want to pipe it to awk and calculate the total for each Header with type X
For the above print, the result would look like this:

Header: A 30
Header: B 14

I am new to unix script programming and tried out different solutions but failed. Any ideas ?
 
Try this (replace cat file2 for your command):
Code:
cat file2| awk '
{if ( $1 != "Type" )
{if ( $1 == "Header:")
 {if ( hn != "" ) print "Header: " hn, sum;
  sum=0; hn=$2}
 else
  sum=sum+$2;}}
 END {print "Header: " hn, sum;}'

----------------------------------------------------------------------------
The person who says it can't be done should not interrupt the person doing it. -- Chinese proverb
 
Or

awk -f namay.awk infile

# namay.awk
/Header/ {
if (hld) print hld, tot
hld = $0
tot = 0
}
/^X/{ tot += $2}
END {
if (hld) print hld, tot
}

CaKiwi
 
Now i want to print the totals for each header to a seperate file with syntax file.$type, e.g. file.X.log and file.Y.log. How can I do this ?

I modified the Code of CaKiwi as follows:

/Header/ {
if (hld) print hld, tot
hld = $0
X = 0
Y = 0
}
/^X/{ X += $2}
/^Y/ {Y += $2}
END {
if (hld) print hld, tot
}



 
Try..
[tt]
function prt() {
if (hld) {
print hld, X > "file.X.log"
print hld, Y > "file.Y.log"
}
hld = $0
X = 0
Y = 0
}
/Header/ {prt()}
/^X/{ X += $2}
/^Y/ {Y += $2}
END {prt()}[/tt]
 
Hi Ygor

Thanx.This worked out ! What if i want to put the values of the X and Y together in one file for each Header and I dont' t know how many Header I have in advance ?
E.g. file.HeaderA.log, fil.HeaderB.log, Header....log
 
Something like this ?
/Header/{h=$2;++t[h]}
/^X/{x[h]+=$2}
/^Y/{y[h]+=$2}
END{for(h in t){
printf "totX=%d\ntotY=%d\n",x[h],y[h] >"fil.Header"h".log
close("fil.Header"h".log)
}}

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top