Friday, December 10, 2010

Renaming Linux files in bulk using wildcards

Until yesterday, I was completely unaware of a useful linux utility called rename. In its place, I used either mv, or mv embedded in a shell script. But clearly, it is a cleaner way of renaming files in bulk.

And it is never to late to discover a useful tool.

Here is one situation where rename is handy. If you had a bunch of files file1, file2, ..., file500, and you wanted to pad zeros to rename these files to file001, file002, ..., file500, you could do that easily with:

rename file file00 file?
rename file file0 file??

or alternatively using regular expressions:

rename ’s/file/file00/’ file?
rename ’s/file/file0/’ file??

It essentially has the following syntax

rename oldname newname *.files
rename "regex-rule" files


Check out these tutorials which explain the rename command with some examples.

One tip I discovered is that the regex syntax works well with Debian based distros (like Ubuntu). Since my desktop at work runs CentOS (RedHat based), it doesn't work quite as well (the other syntax works just fine).

To circumvent the problem, you could download the rename.pl file and run it as shown here.

No comments: