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