Renaming a large number of files can seem like a daunting task, but no worries, your trusty Linux CLI is at your service. For this example, we will rename a number of MP3’s located in multiple subdirectories with a couple very easy commands; “find” and “rename”.
By listing the following directory, you’ll see that the MP3’s have been named with “(LP Version)”, and of course I don’t like this naming convention.
$ cd ~/Music/Metallica/Metallica/
$ ls -1
01 - Enter Sandman (LP Version).mp3
02 - Sad But True (LP Version).mp3
03 - Holier Than Thou (LP Version).mp3
04 - The Unforgiven (LP Version).mp3
05 - Wherever I May Roam (LP Version).mp3
06 - Don't Tread On Me (LP Version).mp3
07 - Through The Never (LP Version).mp3
08 - Nothing Else Matters (LP Version).mp3
09 - Of Wolf And Man (LP Version).mp3
10 - The God That Failed (LP Version).mp3
11 - My Friend Of Misery (LP Version).mp3
12 - The Struggle Within (LP Version).mp3
We’ll use the “rename” command to search for and delete the string ” (LP Version)” in any of the mp3 file names.
Syntax:
$ rename (search command) (files)
$ rename 's/search_for_string/replace_string_with_this/' files
To delete the matching string, simply leave the replace area empty like so:
$ rename 's/search_for_string//' files
Our Example:
$ rename 's/ \(LP Version\)//' *.mp3
Notice, the left and right parentheses need to be preceded with a backslash “\” character, although the spaces do not. The backslash is a metacharacter used to give you control over what your are matching against. For more info, here’s a link to a decent tutorial on the matter.
You can see the results of the command below.
$ ls -1
01 - Enter Sandman.mp3
02 - Sad But True.mp3
03 - Holier Than Thou.mp3
04 - The Unforgiven.mp3
05 - Wherever I May Roam.mp3
06 - Don't Tread On Me.mp3
07 - Through The Never.mp3
08 - Nothing Else Matters.mp3
09 - Of Wolf And Man.mp3
10 - The God That Failed.mp3
11 - My Friend Of Misery.mp3
12 - The Struggle Within.mp3
Now, to rename a large number of files spanning multiple directories, simply combine “rename” with the power of the “find” command.
Syntax:
find . -type f -name *.mp3 -exec rename 's/ \(LP Version\)//' '{}' \;
In this example, we searched starting from the current directory for only files with .mp3 in their file names. We use the find command’s -exec option to execute the rename command against the result set. See the find(1) manpage for more info.
Other useful examples:
Replace all spaces with underscores
rename 's/ /\_/g' *.mp3
Replace all uppercase with lowercase characters
rename 'y/[A-Z]/[a-z]/' *.mp3
Easy stuff, and you don’t even need any fancy applications to do the job!