Perl - Recursively Renaming files on Linux using Regular Expressions

(1/1)

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)
Code:

$ 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!

Code:

$ 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
Code:

$ rename 's/\ /_/g'
$ ls
This_is_a_really_cool_song_(from_my_kick_ass_CD)_-_track_03.mp3


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:

This_is_a_really_cool_song_(from_my_kick_ass_CD)_-_track_03.mp3

What we want:

Really_Cool_Song-Kick_Ass_CD-Track03.mp3

Code:

$ 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
Really_Cool_Song-Kick_Ass_CD-Track03.mp3


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

Code:


$ 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.

Navigation

[0] Message Index