In reference to this comment:
P.S I was able to get this to work from the command line but with only one value as the input.
Have you tried
xargs? With maybe a loop that terminates at end of line/file? Just giving you another option.
I personally agree with Gromit about using PERL or some other language to do this as it is fairly complicated. Using BASH for quick and dirty or for prototyping is great, but you may start running into some limitations. I have tried to solve many an issue using shell scripting of various flavors, but sometimes it just can't do what you need to get done. =8)
Hope I don't get flamed for that. Just my personal opinion.