"Online forums are not code-writing services." What you've described here (vaguely) is a task that will be solved by constructing an appropriate multi-step algorithm. While the community might be able to assist with specific parts of it – such as, "how do I count the number of letters in the first row of the data?" – we really can't be expected to do your work for you, nor to proofread and correct the first script that you maybe threw together. This task has been handed to you, so you're going to be the primary one to fulfill it. We can help you, as a friendly community of experts, but only in targeted ways.
Comment on Re: Cutting text from the end of the file and adding it to the top