Perl - Recursively Renaming files on Linux using Regular Expressions


Richard Marks:
Okay lets say that you have a bunch of files with odd filenames from a non-linux OS  ::)

For example (and no this is not a real filename on my computer I made it up for this example)

$ ls
This is a really cool song (from my kick ass CD) - track 03.mp3

Typing that filename at a terminal would be insane! Especially if you had to type it several times!


$ This\ is\ a\ really\ cool\ song\ \(from\ my\ kick\ ass\ CD\)\ -\ track\ 03.mp3

 :o yuck  :P

Thank God for Perl and Regular Expressions!
Let's make that a much easier to type (and understand) filename!

First I'll do a simple string replace of spaces with underscores

$ rename 's/\ /_/g'
$ ls

The rename command is installed on most linux machines by default.
If its not on yours, then oh-well. Go install it.  ;D

The funky stuff after rename is called a Regular Expression.
namely, this expression is a string replace command.
We have to escape the space by placing an escape-character, the \ character before our space.

The command is 's/search/replace/g'

so put whatever you want to match in place of search and put whatever you want to replace that with in place of replace.

I'll finish with a few more complicated expressions that are really just a bunch of expressions in one line.  ;D

What we have now:


What we want:



$ rename 's/This_is_a_//g;s/really/Really/g;s/cool/Cool/g;s/\(from_my_//g'
$ rename 's/kick/Kick/g;s/ass/Ass/g;s/\)_-_/-/g;s/track_/Track/g'
$ ls

Finally if we want to be able to recursively apply this, then we need to run our regular expressions like this:


$ find start-path -depth | rename regular-expression

Replace the start-path above with whatever path you want to start renaming from.
Replace the regular-expression above with any regular expression you want to apply.

Hope it helped you!  8)
Ask me any questions you may have.


[0] Message Index