Skip to content

Instantly share code, notes, and snippets.

@szero
Last active March 28, 2019 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szero/248a09349606aaa2ea0e4b4d1f6abb78 to your computer and use it in GitHub Desktop.
Save szero/248a09349606aaa2ea0e4b4d1f6abb78 to your computer and use it in GitHub Desktop.
Ghetto file sorting script
#!/usr/bin/env python3
import sys
import re
class fileSort:
def __init__(self):
self.delim = "\n"
self.string_list = list()
if not sys.stdin.isatty():
self.read_pipe()
else:
self.read_files()
def read_files(self):
file_input = sys.argv[1:]
for arg in file_input:
with open(arg, 'r') as stream_in:
self.string_list += [i.strip() for i in stream_in.readlines()]
def read_pipe(self):
if len(sys.argv) == 3:
if sys.argv[1] == "-d":
self.delim = sys.argv[2]
pipe_input = sys.stdin.readlines()
if len(pipe_input) == 1 and self.delim and self.delim != "\n":
pipe_input = [item for item in pipe_input[0].split(self.delim) if item.strip()]
self.string_list = [i.strip() for i in pipe_input]
def __enter__(self):
return self
def __exit__(self, _ex_type, _ex_val, _tb):
pass
@staticmethod
def sort(key):
return [int(i) if i.isdigit() else i for i in re.split(r"(\d+)", key)]
def sort_and_print(self):
for i in sorted(self.string_list, key=self.sort):
print(i, end=self.delim)
print(end="", flush=True)
if __name__ == "__main__":
with fileSort() as fs:
fs.sort_and_print()
@szero
Copy link
Author

szero commented Jun 19, 2018

I made this to be mainly used for sorting files of videos/songs that have numbers in them (TV series or music albums). It will prioritize files with numbers. Its natural sorting with the focus on numbers.

Script accepts list of files or input from an unix pipe.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment