Last active
March 28, 2021 13:14
-
-
Save orangeblock/ee3a01a2810a3da3dbf1e28e042a87a0 to your computer and use it in GitHub Desktop.
Run as `python3 renamer.py /path/to/normalize`. Renames all files and subdirectories at specified root to be UNIX-friendly and not require any quoting.
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/python3 | |
import os | |
import re | |
import sys | |
try: | |
PATH = sys.argv[1] | |
except IndexError: | |
print("Usage: %s /path/to/normalize" % sys.argv[0]) | |
exit(0) | |
REPLACE_REGEX = re.compile(r'[^a-zA-Z0-9_.-]') | |
print("Normalizing directory tree at %s..." % PATH) | |
total = 0 | |
for root, dirs, files in os.walk(PATH, topdown=False): | |
norm_set = set() | |
for i, orig in enumerate(files+dirs): | |
norm = re.sub(REPLACE_REGEX, '_', orig.lower()) | |
if norm.startswith('-'): | |
norm = norm.replace('-', '_', 1) | |
if norm in norm_set: | |
norm = '%s_%d' % (norm, i) | |
norm_set.add(norm) | |
if orig != norm: | |
os.rename(os.path.join(root, orig), os.path.join(root, norm)) | |
total += 1 | |
print("Operation finished, renamed %d files and directories" % total) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment