Here's the output using GNU awk for asorti()
and delete array
:
$ cat tst.awk
function prtCounts( val,sorted,idx) {
if (prev in f1) {
print f1[prev]
asorti(count,sorted)
for (idx=1; idx in sorted; idx++) {
val = sorted[idx]
print count[val], val
}
}
delete count
}
NR==FNR { f1[$2] = $0; next }
{
if ( (FNR>1) && ($4!=prev) )
prtCounts()
count[$10]++
prev = $4
}
END { prtCounts() }
$ gawk -f tst.awk file1 file2
a 1 b c d
1 BALH
2 BLAH
b 2 b c d
1 HAHA
2 ZAHA