It sounds like it should be easily solved with Perl, provided you have a way for the program to determine when to group elements in pairs and when to group them as triads. Without a way to do that, the task is impossible in any language. The only rule you have provided for making that distinction is "if the first field is DG306AE25, then there are three, otherwise there are two", which I rather doubt to be sufficient for handling the full set of your real data.