Renaming lots of files in Linux according to a pattern

Josh Bond picture Josh Bond · Jun 11, 2011 · Viewed 26.1k times · Source

I'm trying to do three things with the mv command, but not sure it's possible? Probably need a script. not sure how to write it. All files are in same folder.

1) Files ending with v9.zip should just be .zip (the v9 removed)

2) Files containing _ should be -

3) Files with Uppercase letter next to a lowercase letter (or lowercase next to an Uppercase) should have a space between them. So MoveOverNow would be Move Over Now and ruNaway would be ruN away [A-Z][a-z] or [a-z][A-Z] becomes [A-Z] [a-z] and [a-z] [A-Z]

Answer

Anthony Michael Cook picture Anthony Michael Cook · Oct 3, 2013

There's a rename command provided with most Debian/Ubuntu based distros which was written by Robin Barker based on Larry Wall's original code from around 1998(!).

Here's an excerpt from the documentation:

  "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.

  For example, to rename all files matching "*.bak" to strip the extension, you might say

          rename 's/\.bak$//' *.bak

  To translate uppercase names to lower, you'd use

          rename 'y/A-Z/a-z/' *

It uses perl so you can use perl expressions to match the pattern, in fact I believe it works much like tchrist's scripts.

One other really useful set of tools for bulk file renaming is the renameutils collection by Oskar Liljeblad. The source code is hosted by the Free Software Foundation. Additionally many distros (especially Debian/Ubuntu based distros) have a renameutils package with these tools.

On one of those distros you can install it with:

$ sudo apt-get install renameutils

And then to rename files just run this command:

$ qmv

It will pop open a text editor with the list of files, and you can manipulate them with your editor's search and replace function.