Let's say we have following Input_file(which willbe created by your 1st requirement, so I have edited it to test it more).
Then following code may help you in same.
Then output will be as follows:
Now you could make All in All command as follows, which you could run with original Input_file(posted in POST#1)
Output will be as follows(as per Input_file into your POST#1).
Please let me know if this helps you, will be glad.