You should use a scripting language (AWK, Perl, Python, etc.) instead of sed. As Matt Might said in his recent article (http://matt.might.net/articles/sculpting-text/): "If you find yourself tempted to use these more advanced [sed] constructs, it's a sign that you want to use a tool like awk or Perl instead."