Friday, February 19, 2021

Rename files with Regex rule

 In Linux, there is very powerful tool to rename files based on pattern we specify.  The pattern follows Perl-like regular expression.


For example, if I have files as follow:



01_-_bohemian_rhapsody_-_queen_-_greatest_hits_cd1.mp3

05_-_bicycle_race_-_queen_-_greatest_hits_cd1.mp3

"07_-_it's_a_hard_life_-_queen_-_greatest_hits_cd2.mp3"

09_-_who_wants_to_live_forever_-_queen_-_greatest_hits_cd2.mp3

11_-_the_miracle_-_queen_-_greatest_hits_cd2.mp3

15_-_friends_will_be_friends_-_queen_-_greatest_hits_cd2.mp3

16_-_the_show_must_go_on_-_queen_-_greatest_hits_cd2.mp3

16_-_we_will_rock_you_-_queen_-_greatest_hits_cd1.mp3

17_-_we_are_the_champions_-_queen_-_greatest_hits_cd1.mp3


and I want to rename them by replacing the "_-_" part to be just "-".  The single command to do that is:




$ rename -n -v 's/_-_/-/g' *

rename(01_-_bohemian_rhapsody_-_queen_-_greatest_hits_cd1.mp3, 01-bohemian_rhapsody-queen-greatest_hits_cd1.mp3)

rename(05_-_bicycle_race_-_queen_-_greatest_hits_cd1.mp3, 05-bicycle_race-queen-greatest_hits_cd1.mp3)

rename(07_-_it's_a_hard_life_-_queen_-_greatest_hits_cd2.mp3, 07-it's_a_hard_life-queen-greatest_hits_cd2.mp3)

rename(09_-_who_wants_to_live_forever_-_queen_-_greatest_hits_cd2.mp3, 09-who_wants_to_live_forever-queen-greatest_hits_cd2.mp3)

rename(11_-_the_miracle_-_queen_-_greatest_hits_cd2.mp3, 11-the_miracle-queen-greatest_hits_cd2.mp3)

rename(15_-_friends_will_be_friends_-_queen_-_greatest_hits_cd2.mp3, 15-friends_will_be_friends-queen-greatest_hits_cd2.mp3)

rename(16_-_the_show_must_go_on_-_queen_-_greatest_hits_cd2.mp3, 16-the_show_must_go_on-queen-greatest_hits_cd2.mp3)

rename(16_-_we_will_rock_you_-_queen_-_greatest_hits_cd1.mp3, 16-we_will_rock_you-queen-greatest_hits_cd1.mp3)

rename(17_-_we_are_the_champions_-_queen_-_greatest_hits_cd1.mp3, 17-we_are_the_champions-queen-greatest_hits_cd1.mp3)


(the argument "-n" above is to tell rename not to actually perform renaming, but just to display what it would do).  I use "/g" in the regular expression to tell it to rename all occurrences of "_-_" throughout the file name, not just for the first time it encounters it.

No comments:

Post a Comment