Rename files en masse

October 26th, 2012 by Erin Scott

There are more than a few shareware utilities for both Windws and Mac that give a user the ability to rename a bunch of files according to a certain criteria.  Gui utilities are always nice but what if you’re logged into a webserver and need to rename all .JPG files to .jpg?

There’s a simple perl script that give you the ability to rename all files in a directory according to the powerful rules of regular expressions.  Here are some example ways to use the script.

 

The following renames all files ending in .JPG to .jpg.

% rename ‘s/\.JPG$/jpg/’ *.JPG

 The next one converts all uppercase filenames to lowercase except for Makefiles.

% rename ‘tr/A-Z/a-z/ unless /^Make/’ *
 
The next one removes the preceeding dot in front of a filename unless it’s a .DS_Store file
 
% rename ‘s/^\.// unless /^.DS_Store/’ *

The next one appends the date to all text files in the current directory.

% rename ‘$_ .= “.2012-10-26″‘ *.txt
 

The last and arguably most useful way to use this tool is to pipe it through find.  This example renames all files in /var/www from .JPG to .jpg.

% find /var/www -name ‘*.JPG’ -print | rename ‘s/\.JPG$/\.jpg/’
 
 

Note: There are 2 variables you can set in the script.  The first is a list of files to ignore and the second is to turn on “dry run” mode. This will allow you to see what the script is going to do before irreversibly changing the file name.

 

Here is the script

Comments are closed.