Third party cookies may be stored when visiting this site. Please see the cookie information.

PenguinTutor YouTube Channel

Linux - changing the case of a filename using the rename command

Although knowledge of the command line is not required to use Linux sometimes it can come in very helpful. renaming files is one area where it is often quicker and easier to batch rename a number of files using a command line program or short script.

mv

The normal command for renaming a file is mv (move). This takes two arguments the first being the current filename and the second being the new filename.

eg.
mv currentname.txt newname.txt

There is however another command called rename. Unlike mv, rename is not built in to the shell, but is commonly installed on most Linux systems. It's actually a perl script. On my system the /usr/bin/rename command links to the file /usr/bin/prename.

rename

The rename command allows you to use perl regular expressions to define this files will be renamed and how.

The command takes the form of a regular expression followed by the files to apply the changes to. This is much like using a regular expression on a string in perl, but renames the files.

For example to rename files with JPG to jpg (if required due to the case-sensitive filenames in Linux) then the following can be used:

rename 's/JPG/jpg/' *

It substitutes (s) any occurrences of JPG and replaces them with jpg. Note that this will rename the first occurrence of JPG within the filename and not just the extension.

A more useful way would be:
rename 's/\.JPG/\.jpg/' *       #rename the first occurrence of .JPG

or
rename 's/JPG$/jpg/' *       #rename from JPG to jpg, but only if it matches on the last 3 digits.

To understand more about regular expressions see: Introduction to regular expression programming or perl regular expression quick reference guide.

If you wanted to convert an entire filename from upper case to lower case then you need the translate 'y' option as shown in the example below.

rename 'y/A-Z/a-z/' *

There are three options than can change how the command works:
-n (don't actually make any changes, useful for testing)
-v (show changes made useful to show what renaming is done)
-f (force - overwrite existing files)

The rename command is prefixed with:
s = substitute
y = translate

More information