code: def exonunion(args):
      
      p = OptionParser(exonunion.__doc__)
      opts, args = p.parse_args(args)
  
      if len(args) != 1:
          sys.exit(not p.print_help())
  
      gencodebed, = args
      beds = BedTool(gencodebed)
      # fields[3] is gene_id; fields[6] is gene_name
      for g, gb in groupby(beds, key=lambda x: x.fields[3]):
          gb = BedTool(gb)
          sys.stdout.write(str(gb.sort().merge(c="4,5,6,7",
                               o=','.join(['first'] * 4))))
docs: %prog exonunion gencode.v26.annotation.exon.bed
  
      Collapse overlapping exons within the same gene. File
      `gencode.v26.annotation.exon.bed` can be generated by:
  
      $ zcat gencode.v26.annotation.gtf.gz |  awk 'OFS="\t" {if ($3=="exon")
      {print $1,$4-1,$5,$10,$12,$14,$16,$7}}' | tr -d '";'