Last active
November 3, 2023 15:08
-
-
Save highfestiva/a8a685ce048e23f9c3d19ddbe7a38258 to your computer and use it in GitHub Desktop.
Recursively rename multiple files
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 | |
import glob | |
import os | |
import re | |
import sys | |
def printUsage(): | |
print("%s <wildcard> <replacement wildcard>" % sys.argv[0]) | |
print("Example: %s * Ui*" % sys.argv[0]) | |
print("Only one asterisk may be used in the wildcards.") | |
def renameFiles(target_dir, wildcard, replacement): | |
wildcardRegex = wildcard.replace('.', '\\.').replace('*', '(.*)') | |
replacementRegex = replacement.replace('*', '\\1') | |
infiles = glob.glob(target_dir + '/' + wildcard) | |
for infile in infiles: | |
outfile = re.sub(wildcardRegex, replacementRegex, infile); | |
print(infile, "->", outfile) | |
os.rename(infile, outfile) | |
def main(): | |
if len(sys.argv) == 3: | |
wildcardList = sys.argv[1].split("*") | |
replacementList = sys.argv[2].split("*") | |
if len(wildcardList) == 2 and len(replacementList) == 2: | |
for root,ds,files in os.walk('.'): | |
for d in ds: | |
td = root + '/' + d | |
renameFiles(td, "*".join(wildcardList), "*".join(replacementList)) | |
else: | |
printUsage() | |
else: | |
printUsage(); | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment