Skip to content

Instantly share code, notes, and snippets.

@emdete
Created August 18, 2019 18:42
Show Gist options
  • Save emdete/4b3a54d49bfaec974ca3d84d98ec4a92 to your computer and use it in GitHub Desktop.
Save emdete/4b3a54d49bfaec974ca3d84d98ec4a92 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
#
# This is regren, a regular expression renamer. It allows to rename files by
# regular expressions given on the command line, but instead of actually doing
# that job it spits out the commands for a shell to do so. You just start
# preparing your command line and check the result and if you are happy with it
# you add a `| sh` to commit the change to the filesystem.
#
# The first argument is the regex to search in the filename, if no match is
# found not rename is issued.
#
# The second argument is the replacement pattern.
#
# All the next arguments are filenames to rename. The program does not
# distinguish between basnames or pathes, everthing will be considered.
#
# EXAMPLES
#
# If you want to change 'a' to 'b' for some filenames:
#
# $ regren a b a ab ca
# mv -iv 'a' 'b'
# mv -iv 'ab' 'bb'
# mv -iv 'ca' 'cb'
#
# If you want to rename imagenames containing date/timestamp to proper
# iso-format you can use:
#
# regren '(IMG|VID|Screenshot)_(....)([0-9].)(..)[-_]?(..)(..)(.*)' '\2-\3-\4-\5-\6-\7' *
#
# or (for a different format):
#
# regren '(\d\d\d\d)(\d\d)(\d\d)[-_]?(..)(..)(.*)' '\1-\2-\3-\4-\5-\6' *
#
from re import compile
def main(regex, replacement, *names):
regex = compile(regex)
for name in names:
if '/' in name:
path, filename = name.rsplit('/', 1)
path = path + '/'
else:
path, filename = '', name
newfilename = regex.sub(replacement, filename)
if filename != newfilename:
print("mv -iv '{}' '{}'".format(name, path + newfilename))
if __name__ == '__main__':
from sys import argv
main(*argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment