I would check out the 'join' utility. If you have two files, A and B, comma-delimited, they are -sorted- (see the sort utility), and you want all lines that have the first column in common, then: join -j 1 -t ',' A B
This ought to work fine! Then just iterate across all of the files, iterating as suits you best.
Mark