Skip to content

Instantly share code, notes, and snippets.

@laurentperrinet
Created August 4, 2020 08:33
Show Gist options
  • Save laurentperrinet/5d550a2c08d81cdd04333602d0f36f36 to your computer and use it in GitHub Desktop.
Save laurentperrinet/5d550a2c08d81cdd04333602d0f36f36 to your computer and use it in GitHub Desktop.
A short python script to rename a bunch of files
#!/usr/bin/env python3
"""
rename a bunch of files given a glob pattern and change A into B
rename_files.py -g "**/*.pdf" -a "\\" -b "_" --dry-run
rename_files.py -g "**/*" -a "\\" -b "_"
"""
import argparse
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-g", "--glob-pattern", required='*', help="glob pattern")
ap.add_argument("-a", "--alice", required=True, help="pattern to match")
ap.add_argument("-b", "--bob", required=True, help="pattern to replace")
ap.add_argument("-n", "--dry-run", help="dry run.", action='store_true')
# args = vars(ap.parse_args())
args = ap.parse_args()
print (args)
import shutil
import os, glob, json
for fname in glob.glob(args.glob_pattern):
if args.alice in fname:
fname_ = fname.replace(args.alice, args.bob)
if args.dry_run :
print(fname, '>>', fname_)
else:
shutil.copy(fname, fname_)
os.remove(fname)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment