I recently had the need to rename a series of sequential files and add leading zeros to the number sequence within the filename.  i.e. I had files:

file-10.txt
file-1.txt
file-20.txt
file-5.txt
file-9.txt

and I wanted to rename them to:

file-01.txt
file-05.txt
file-09.txt
file-10.txt
file-20.txt

so they would be in lexical order and easier to read a directory listing of the files.

I had previously used a rename command in linux written in Perl that used regular expressions but I was on an unfamiliar linux system and it had a completely different rename command.  After some research I discovered that there are two very different rename commands within Ubuntu (note that I am using Ubuntu 10.04)

  • prename – a Perl renaming utility (located in /usr/bin/)
  • rename.ul – a renaming utility (also located in /usr/bin/) that is part of the util-linux or util-linux-ng package

There is a symbolic link /usr/bin/rename that points to /etc/alternatives/rename which in turn points to /usr/bin/prename.  So the default behavior on my ubuntu system for the rename command would be to call prename.

To accomplish the renaming example above with prename use the following command

$ prename 's/file-/file-0/' file-?.txt

To do it using rename.ul use the following command

$ rename.ul file- file-0 file-?.txt

I think the rename.ul is much quicker and easier in a pinch, but the prename command is much more powerful and might be needed for more complex renaming scenarios.

Here’s another good link to how to batch rename files in linux:  http://tips.webdesign10.com/how-to-bulk-rename-files-in-linux-in-the-terminal

«