Revision 1658
Added by Aaron Marcuse-Kubitza over 12 years ago
bin/sort_filenames | ||
---|---|---|
1 |
#!/usr/bin/env python |
|
2 |
# Sorts a list of filenames, comparing embedded numbers numerically instead of |
|
3 |
# lexicographically. This will sort e.g. "a.2" after "a.10" instead of before. |
|
4 |
# Usage: self [filename...] >sorted_list |
|
5 |
|
|
6 |
import re |
|
7 |
import sys |
|
8 |
|
|
9 |
def str2tuple(str_): |
|
10 |
parts = re.split(r'(\d+)', str_) |
|
11 |
for i, part in enumerate(parts): |
|
12 |
if i % 2 == 1: # every other part is a delimeter match = a number |
|
13 |
parts[i] = int(part) |
|
14 |
parts.append('') # padding to ignore original str (added below) when sorting |
|
15 |
parts.append(str_) # save original str for easy conversion back to str |
|
16 |
return tuple(parts) |
|
17 |
|
|
18 |
def tuple2str(tuple_): return tuple_[-1] |
|
19 |
|
|
20 |
def main(): |
|
21 |
filenames = map(str2tuple, sys.argv[1:]) |
|
22 |
filenames.sort() |
|
23 |
for filename in map(tuple2str, filenames): sys.stdout.write(filename+'\n') |
|
24 |
|
|
25 |
main() |
|
0 | 26 |
Also available in: Unified diff
Added sort_filenames to sort a list of filenames, comparing embedded numbers numerically instead of lexicographically