This is usually the point at which it might be better to use a "real" programming language instead of shell scripting. What you're trying to do could be quite easily accomplished using Python and its standard library.
You could then add a #!/usr/bin/python at the top of the Python file and make it executable.