Sunday, 7 February 2010

Linux: Mass rename of files

When people give me files, especially images, coming from windows machines I always have problems with capitalised extensions. JPEG format files for instance appear as image.JPG instead of image.jpg. Worst case is that in some collections some file extensions appear capitalised while others in lower case.

I have searched the web for some simple solution to this problem and ended up seeing sed commands and pipes that UNIX gurus are so fond off,

So, if you wanted to rename all the .php3 to .php, this would be the command:
ls -d *.php3 | sed 's/\(.*\).php3$/mv "&" "\1.php"/' | sh

As Fortune keeps reminding me, there is more than one way to skin a cat, so a more complete discussion on mass renaming with Linux can be found on Gareth Anderson's GNU/Linux Command-Line Tools Summary book article directly accessible from here.

Anyway, after a little bit of googling, it turned out to my surprise that the simplest way to do this was inside my own Fedora distro. The magic command is rename and the man entry is small, simple and accurate :

RENAME(1)                  Linux Programmer’s Manual                 RENAME(1)

       rename - Rename files

       rename from to file...
       rename -V

       rename will rename the specified files by replacing the first occurrence of from in their name by to.

       -V, --version
              Display version information and exit.

       For example, given the files
              foo1, ..., foo9, foo10, ..., foo278, the commands

              rename foo foo0 foo?
              rename foo foo0 foo??

       will turn them into foo001, ..., foo009, foo010, ..., foo278.

              rename .htm .html *.htm

       will fix the extension of your html files.

       mmv(1), mv(1)

       The   rename   command   is   part   of   the   util-linux-ng   package   and   is   available  from  ftp://ftp.ker-

                                1 January 2000                       RENAME(1)

The rename command is also available on all EL clones like (CentOS and Oracle EL).