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

Help me with counting in an array

Status
Not open for further replies.

mrr

Technical User
May 3, 2001
67
US
I have a data file such as
11111,22222,1
11112,22223,1
11113,22224,1
22222,33333,2
22223,33334,2
22224,33335,2
22225,33336,3
and so on.

The input format is x,y,id name

I would like the output to show
the number of xy pairs for each group of similar ids and
the output format would be as follows:
3,1
11111,22222,1
11112,22223,1
11113,22224,1
3,1
22222,33333,2
22223,33334,2
22224,33335,2
1,1
22225,33336,3
and so on.

I know I have to read entire file into an array but can't
seem to get the output in the prefered format.

Thanks for the help.
mrr

 
Hi mrr,

This works on your data sample:

#!/bin/sh
#
# This shell script sorts on field 3,
# pipes into awk, then, displays and
# writes the data into an output file.
#
# Usage:
# file $1 $2 <CR>
#
# Notes:
# Sorts data file if unsorted.
#
#

sort -t , -k 3,3 $1 |
awk 'BEGIN { FS = &quot;,&quot; }

NR == 1 {
prev = $3
}

$3 == prev {
++count
lines[++i] = $0
}

$3 != prev {
print count&quot;,1&quot;
for ( j =1; j <= i; j++)
print lines[j]
for (all in lines)
delete lines[all]
prev = $3
i = 0
lines[++i] = $0
count = 1
}

END {
print count&quot;,1&quot;
for (k=1; k <= i; k++)
print lines[k]

}' | tee $2

#
# Hope this helps you!
#



flogrr
flogr@yahoo.com

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top