Search This Blog

Sunday 25 April 2010

Ubuntu: Bulk rename

Examples:

Maybe you have a digital camera that takes photos with filenames something like 00001234.JPG, 00001235.JPG, 00001236.JPG. You could make the .JPG extension lowercase with the following command executed from the same directory as the images:

rename -v 's/\.JPG$/\.jpg/' *.JPG

Here is the output of the above command:
 
$ rename -v 's/\.JPG$/\.jpg/' *.JPG
00001111.JPG renamed as 00001111.jpg
00001112.JPG renamed as 00001112.jpg
00001113.JPG renamed as 00001113.jpg

That is simple enough, as it is similar to the .html example earlier. You could also bulk rename them with something descriptive at the beginning like this:

Tip: Before trying more complicated renaming like in the example below, do a test run with the -n option as described at the beginning of this tutorial.

rename -v 's/(\d{8})\.JPG$/BeachPics_$1\.jpg/' *.JPG

That will change filenames that have the pattern ########.JPG (8 numbers and capital .JPG) to something like BeachPics_########.jpg (the same 8 numbers and changing the extension to lowercase .jpg). Here is a test run with the -n option:
 
$ rename -n 's/(\d{8})\.JPG$/BeachPics_$1\.jpg/' *.JPG
00001111.JPG renamed as BeachPics_00001111.jpg
00001112.JPG renamed as BeachPics_00001112.jpg
00001113.JPG renamed as BeachPics_00001113.jpg

Here's a quick breakdown of the Perl substitution with the regular expression above.
The highlighted section below means to count 8 digits. The parentheses mean to save those 8 digits for later because they are going to be used again in the second half of the substitution:

's/(\d{8})\.JPG$/BeachPics_$1\.jpg/'

In the highlighted section below, it adds the string BeachPics, and underscore, and then the text in parentheses from the first half of the substitution. $1 will insert the string from the first set of parentheses that it finds — in this case the 8 digits. If you have more than one set of parentheses you can access the second set with the Perl variable $2 and so on.

's/(\d{8})\.JPG$/BeachPics_$1\.jpg/'