As shell scripts are not flexible enough, i would suggest to use a python script for this,
which i will make for you, you will notice no difference as it will run like a normal script(just replace the shebang header),
python had many complex tools and better regex support to do this