/tools/filters/sorter.py

https://bitbucket.org/h_morita_dbcls/galaxy-central · Python · 49 lines · 30 code · 5 blank · 14 comment · 10 complexity · b5e9e30e84c8970f8eae2c4f9933d386 MD5 · raw file

  1. """
  2. Sorts tabular data on one or more columns.
  3. usage: %prog [options]
  4. -i, --input=i: Tabular file to be sorted
  5. -o, --out_file1=o: Sorted output file
  6. -c, --column=c: First column to sort on
  7. -s, --style=s: Sort style (numerical or alphabetical)
  8. -r, --order=r: Order (ASC or DESC)
  9. usage: %prog input out_file1 column style order [column style ...]
  10. """
  11. import os, re, string, sys
  12. from galaxy import eggs
  13. import pkg_resources; pkg_resources.require( "bx-python" )
  14. from bx.cookbook import doc_optparse
  15. def stop_err( msg ):
  16. sys.stderr.write( "%s\n" % msg )
  17. sys.exit()
  18. def main():
  19. #Parse Command Line
  20. options, args = doc_optparse.parse( __doc__ )
  21. try:
  22. inputfile = options.input
  23. outputfile = '-o %s' % options.out_file1
  24. columns = [options.column]
  25. styles = [('','n')[options.style == 'num']]
  26. orders = [('','r')[options.order == 'DESC']]
  27. col_style_orders = sys.argv[6:]
  28. if len(col_style_orders) > 1:
  29. columns.extend([col_style_orders[i] for i in range(0,len(col_style_orders),3)])
  30. styles.extend([('','n')[col_style_orders[i] == 'num'] for i in range(1,len(col_style_orders),3)])
  31. orders.extend([('','r')[col_style_orders[i] == 'DESC'] for i in range(2,len(col_style_orders),3)])
  32. cols = [ '-k%s,%s%s%s'%(columns[i], columns[i], styles[i], orders[i]) for i in range(len(columns)) ]
  33. except Exception, ex:
  34. stop_err('Error parsing input parameters\n' + str(ex))
  35. # Launch sort.
  36. cmd = "sort -f -t $'\t' %s %s %s" % (' '.join(cols), outputfile, inputfile)
  37. try:
  38. os.system(cmd)
  39. except Exception, ex:
  40. stop_err('Error running sort command\n' + str(ex))
  41. if __name__ == "__main__":
  42. main()