CAN AWK KEEP COUNT

Kris Stephens [Hail Eris!] krs at uts.amdahl.com
Sat Mar 23 07:18:20 AEST 1991


In article <356 at marst2> vwa0201 at marst2 (Larry Baca) writes:
>In one portion of a script I have written (csh), I need to keep a running total
>of certain fields within a record found by grep. My grep statement looks
>something like this:
>
>grep $pattern $infile | tee $outfile | cut -c49-100 | awk ......
>
>My problem is in awk, I want to feed "awk" cols 49-100 of the greped record. 
>
>The "cut" record consists of 5 numeric fields of 10, 12, 10, 10, and 10 cols 
>in length, no spaces. 
>
>I want awk to keep a running total for each field and spit the grand totals 
>out at the end. As you can see I am also writing the entire record to $outfile.
>
>I would also like "awk" to make the grand totals available to the rest of
>the script.
>
>I might add the file I am working with is around 900K 100 col rcds, so maybe
>awk isn't the way to go.

Well, I'd be approaching it like:

-- getstuff.sh --
:
# snag pattern $1 from file $2, write it to $3, and set the totals in
# shell variables $1 through $5.

pattern="$1"
infile="$2"
outfile="$3"

# test values assigned above, then....

#
# grep's still faster as our sieve that to ask awk to filter infile...
#
set -- `grep "$pattern" "$infile" |
	awk '		{
			print > outfile
			tot[1] += substr($0, 49, 10)
			tot[2] += substr($0, 59, 12)
			tot[3] += substr($0, 71, 10)
			tot[4] += substr($0, 81, 10)
			tot[5] += substr($0, 91, 10)
			}
		END	{
			close(outfile)
			print tot[1]+0, tot[2]+0, tot[3]+0, tot[4]+0, tot[5]+0
			}' \
		outfile="$outfile" -`

for i in 1 2 3 4 5
do
	eval "echo \"Total $i: \$$i\""
done
-- getstuff.sh --

...Kris
-- 
Kristopher Stephens, | (408-746-6047) | krs at uts.amdahl.com | KC6DFS
Amdahl Corporation   |                |                    |
     [The opinions expressed above are mine, solely, and do not    ]
     [necessarily reflect the opinions or policies of Amdahl Corp. ]



More information about the Comp.unix.questions mailing list