Saturday, April 21, 2012

rename: A powerful command line utility on linux.

This is regaring the rename command line utility on Ubuntu Linux.  Your distribution may have either no command of this name, or another command named this that is less powerful.   Read the man page for your distribution to see what you have:

man rename

If you get 'no manual entry for rename' then your distribution does not have it installed, you can explore how to find and install modules for your distribution.  For most Debian based systems a 'sudo apt-get install rename" should do the trick.

My Ubuntu system gives the following man page:

RENAME(1)              Perl Programmers Reference Guide              RENAME(1)

       rename - renames multiple files

       rename [ -v ] [ -n ] [ -f ] perlexpr [ files ]

       "rename" renames the filenames supplied according to the rule specified
       as the first argument.  The perlexpr argument is a Perl expression
       which is expected to modify the $_ string in Perl for at least some of
       the filenames specified.  If a given filename is not modified by the
       expression, it will not be renamed.  If no filenames are given on the
       command line, filenames will be read via standard input.

And then follows with a few examples and explanations of the options.

The rename command uses regular expressions to manipulate the file names in a directory.  Because regular expressions are so powerful this tool can do almost anything.

Important safety note... because this tool is so powerful and there is no undo on renaming files, it is important to test things before you totally destroy all the filenames in a directory.  And you can easily destroy things.  There is an option flag of '-n' that will just print what it would have done, without actually changing anything.  I implore you to use this option and study the results before you run the command for real.

I mainly wanted to use this tool to rename filenames of books.  I wanted the author names formated in a specific way, and it was too much work to go through thousands of files and rename them one at a time by hand.  So I discovered the rename command that was already installed on my computer. 

How to rename author names in directory


First Last
First Middle Last
First M. Last
F. M. Last


Last, First
Last, First Middle
Last, First M.
Last, F. M.

Use these two commands:

rename ’s/([A-Za-z]+) ([A-Za-z]+)/$2, $1/’  *
rename ’s/([A-Za-z.]+) ([A-Za-z.]+) ([A-Za-z]+)/$3, $1 $2/’  *

Other functions:

Changing the extension of a file:

rename ’s/\.zip/.cbz/’ *.zip

The command is good to clean up multiple spaces in a file name as well.

Getting rid of extra characters in a file name:
rename ’s/–#//’ *.zip
rename ’s/Filename –#/Filename /’ *.cbz

The last two match filenames with anything following the Filename space part.

No comments:

Post a Comment