Batch renaming files in shell

Did you ever have to rename a lot of files using a similar pattern? And did you end up sitting in front of Finder or whatever your favorite file manager is and stripped of a certain prefix from the file-name or changed the extension? Well, I did. But as long as you have a terminal at hand, you can do better. Here is how.

Adjusting a prefix

Let’s say you want to rename your ripped Futurama episodes. The current naming convention is “Futurama 02×12 Raging Bender.mp4″. So it’s Futurama followed by a space and the season-episode identifier (season 2, episode 12), then the episode’s name and finally the extension.

First of all, we strip off “Futurama” and the space, because all the files are stored in a directory named “Futurama”, so we don’t need that info in the file-name anymore.

for i in Futurama*; do mv "$i" "${i##Futurama }"; done

What we do here is to loop over all files in the current directory that start with “Futurama” and assign the file-name to the variable $i. We use $i as parameter to the mv command for actually renaming the file. The interesting part is its second parameter, ${i##Futurama }

Here we apply a modifier to the variable $i, which adjusts the returned value, but not the variable’s value itself. In this case, the modifier is ## which removes a certain prefix from the variable, “Futurama ” (including the space), leaving “02×12 Raging Bender.mp4″.

Make sure to surround both parameters by quotation marks, because the file names may contain spaces.

Modifying the suffix

Now that we have removed the leading “Futurama “, we want to adjust the mp4-extension. iTunes prefers m4v, so let’s change this.

for i in *.mp4; do mv "$i" "${i%mp4}m4v"; done

It’s very similar to what we did in the first part, except that we loop over all mp4-files and use a different variable modifier.

The % modifier removes the given text from the end of the variable’s value, so ${i%mp4} removes the mp4-extension, returning “02×12 Raging Bender.”. To add the new m4v-extension, we just include it after the braces.

That’s all, the files are renamed the way we wanted to. There are two tips when using this way to rename files. First of all, put the file-name in quotation marks, otherwise you will run into problems if files contain spaces, leading to undesired behaviour or errors in the best case, to loss of data in the worst case. And the second recommendation is to echo out the result first before actually using mv, just to make sure the modifier produces the expected result.

Do you have other tips for batch renaming files? Please explain them in the comments.

Share and Enjoy:
  • Facebook
  • Twitter
  • del.icio.us
  • Diigo
  • Google Bookmarks
  • Digg
  • Reddit
  • StumbleUpon
  • MySpace
  • MisterWong
  • DZone
  • Slashdot
  • PDF
  • Print
  • email