Skip to content

Instantly share code, notes, and snippets.

@tcahill
Created March 24, 2013 05:55
Show Gist options
  • Save tcahill/5230742 to your computer and use it in GitHub Desktop.
Save tcahill/5230742 to your computer and use it in GitHub Desktop.
Replace a regular expression in filename(s) with another expression
#!/usr/bin/python
import argparse
import os
import re
parser = argparse.ArgumentParser(description='Replace regex in filenames.')
parser.add_argument('files', metavar='F', nargs='+',
help='Files to operate on (Ignores directories)')
parser.add_argument('match', metavar='M', nargs=1,
help='Regular expression to replace in filenames')
parser.add_argument('replace', metavar='R', nargs=1,
help='Expression to replace M with.')
args = parser.parse_args()
print args.files
for old in args.files:
new = re.sub(args.match[0], args.replace[0], old)
try:
os.rename(old, new)
except OSError:
print "Invalid file"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment