Created
January 8, 2018 20:15
-
-
Save Tomin1/8f77bad1a720645faf3f9f0669e91fe8 to your computer and use it in GitHub Desktop.
reordering scripts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # Public domain | |
| import argparse | |
| import os | |
| import os.path | |
| import shutil | |
| import sys | |
| def reorder(directory, sorted_, recurse, verbose): | |
| if verbose: | |
| print("{}: Reordering".format(directory)) | |
| backup = directory + '~' | |
| if os.path.exists(backup): | |
| print("{}: Exists".format(backup), file=sys.stderr) | |
| os.replace(directory, backup) | |
| os.mkdir(directory) | |
| for file in sorted_(os.listdir(backup)): | |
| target = os.path.join(directory, file) | |
| os.replace(os.path.join(backup, file), target) | |
| if verbose: | |
| print("{}: Moved back".format(target)) | |
| if recurse and os.path.isdir(target): | |
| reorder(target, sorted_, recurse, verbose) | |
| os.rmdir(backup) | |
| def main(): | |
| parser = argparse.ArgumentParser("Reorder files in a directory") | |
| parser.add_argument('directories', metavar='directory', nargs='+') | |
| parser.add_argument('-v', '--verbose', action='store_true', default=False) | |
| parser.add_argument('-r', '--recursive', action='store_true', | |
| default=False) | |
| parser.add_argument('-n', '--natsort', action='store_true', default=False) | |
| args = parser.parse_args() | |
| if args.natsort: | |
| from natsort import natsorted | |
| sorted_ = natsorted | |
| else: | |
| sorted_ = sorted | |
| for directory in args.directories: | |
| if directory.endswith('/'): | |
| directory = directory[:-1] | |
| if not os.path.isdir(directory): | |
| print("{}: Not a directory".format(directory), file=sys.stderr) | |
| continue | |
| reorder(directory, sorted_, args.recursive, args.verbose) | |
| if __name__ == "__main__": | |
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # Public domain | |
| DIR=$1 | |
| SORT=sort | |
| if [ -n "$(which natsort 2> /dev/null)" ] | |
| then SORT=natsort | |
| fi | |
| if [ -d "$DIR~" ] | |
| then printf "Directory %s~ already exists. Aborting.", $DIR | |
| exit 2 | |
| fi | |
| mv "$DIR" "$DIR~" | |
| mkdir "$DIR" | |
| for file in $(ls "$DIR~" |$SORT) | |
| do mv "$DIR~/$file" "$DIR/$file" | |
| done | |
| rmdir "$DIR~" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment