Hello and welcome to the forum,
Urgent Help Required!
Perceptions vary. . . If this was truly urgent, you would have already written the code rather than posting on some forum where the request might not be seen for hours or days. . .
Many things can be done with the sort products (and you did not mention which sort is used on your system). However, what you have posted will be more difficult (if even possible - via the sort or even a programming language). This is beacuse your sample data and your "rules" are inconsistent (at least to me).
The "rules" say each record is to be repeated 3 times. Why are there only 2 records with 5001? Why is there only 1 record with 5004?
Hopefully, you know what is really needed and can implement cobol or something else to generate the needed output. . .