More on Rename

In the previous post I mentioned the rename command, but said that I didn’t know too much about it.   Well after some reading, and messing around I have learned a little bit more, so guess I should share.

Here is the general set up of the command;
rename [options] 's/expr1/expr2/' expr3
expr1, expr2, and expr3 are Perl regular expressions. Basically it will replace expr1 with expr2 in every file that matches expr3.
The options are;
-n (do nothing, just print out what the result would be if the command were to run)
-f (force overwrite of existing files) and
-v (verbose, print out progress while command runs).

For the sake of these example suppose that your folder contains the following files:

Example 1

Suppose that we want to change the file extensions to .jpg instead. Then just type rename 's/\.JPG/\.jpg/' *.JPG So instead of having Pic_00019876_new.JPG you have Pic_00019876_new.jpg

Example 2

Now suppose that you want to remove the leading 0s from the file number. For this you would type something like
rename 's/Pic_(\d{3})(\d{5})_new\.JPG/Pic_$2_new\.JPG/' *.JPG
The $2 says to use the 2nd matched group, and the (\d{X}) matches X digits.
Here Pic_00019876_new.JPG becomes Pic_19876_new.JPG

Example 3

For the hell of it say that you want to remove the ‘Pic’ prefix, make the first 4 digits the last 4, make .JPG into .jpg and put ‘new’ at the front. For this you could run
rename 's/Pic_(\d{4})(\d{4})_(new)\.JPG/$3_$2$1\.jpg/' *.JPG
One word of caution, make sure the escape the ‘.’ or you might get unexpected results. Now Pic_00019876_new.JPG becomes new_98760001.jpg

Hope that those examples were useful. the ‘s/…’ says that it will be matching a string. There are other things you can use instead of ‘s’, but I don’t know what they are and am not a Perl guru so I wouldn’t be able to tell you. I do however, know that ‘y/…’ is used in changing the case of all characters.

For further reading I would suggest this site.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: