This sounds a bit too involved for a shell script.
I recommend that you learn Perl, which will be adequate for this.
Instead of Perl, you could use awk. That would probably also work, but Perl will give you a more general tool that you can use in more future situations than awk.
|