Problems like this are easily solved using a scripting language like AWK, PERL, or Python.
If you need to manipulate text files very often, it is well worth your time to learn one (or more) of these languages.
AWK is the easiest to install (one exe file; I recommend gawk for windows) and use (not a ton of functions, very C-like if you are a C programmer).
PERL and Python have much more ability to interact with other system components (that is, they can do a lot more than manipulate text), but they require you to install a bunch of files and are a bit harder to learn.
Python is the it scripting language right now, so you’ll find lots of people willing to help you with that.