Используйте regex для изменения (реорганизации) нескольких имен файлов в Bulk File Renamer

905
LincM

У меня есть несколько тысяч файлов MP3, вложенных в папки, которые я бы хотел переименовать.

В настоящее время файлы имеют следующее соглашение об именах:

"tracknumber_artistname_-_songname_MP3COLLECTION.mp3" 

Например:

"01_Michael_Jackson_-_Wanna_Be_Startin'_Something_MP3COLLECTION.mp3" 

Тем не менее, я хотел бы реорганизовать эти файлы, переместив имя исполнителя после названия песни, убрав излишнюю дробь в конце и заменив все подчеркивания пробелами, что привело к приведенному выше соглашению и приведению примера, подобного следующему:

"tracknumber songname - artistname.mp3" "01 Wanna Be Startin' Something - Michael Jackson.mp3" 

У меня есть переименователь Bulk File, который дает опции для Regex, но я не знаю, как это сделать. Какие-либо предложения? Я также открыт для использования различных инструментов или даже методов, если переименование файлов не является лучшим вариантом.

Примечание: я первоначально разместил это на StackExchange, но мне посоветовали опубликовать это здесь вместо этого, потому что там не по теме.

2

2 ответа на вопрос

1
SadBunny

In Windows? I don't know "Bulk File Renamer". I would use Total Commander's "Multi Rename" tool. Better yet, I'd probably work with perl or awk from a Cygwin terminal for a more comprehensive script solution. That would go too far for here though. Just from a regex perspective, this works for me in TC with your filename (but only if files do not contain extra "-" or "." in the artist or song title fields), should probably work in any regex-supporting bulk rename tool without too much trouble because I don't think I used any fancy advanced RegEx stuff, like posix character classes (":digit:" and such)...

If you're using TC, you want to tick the "[E]" and the "RegEx" checkboxes, and untick the other three, in the Search & Replace part of the Multi-Rename tool. I tested this whole thing in TC myself, so please appreciate the time I took for you :) If you use another tool and it does not work, search its RegEx-related help for "backreferences" as some tools tend to use different standards for RegEx bacrefs. (It's the $1 $2 $3 etc. in my code below that refers to something in parenthesis in the search.)

NOTE If you're gonna bulk-rename, please, for the love of God, make a backup of your entire collection first. You never know. I'm not responsible, blah blah.

FIRST: make the separator in _ "_-_" instead of the current "_". Because "_-_" seems like a useful separator that would not often accidentally appear in any normal text. Also, let's snuff out the "_" part right here.

search for: (([0-9]+)_)(.*)_(.*)(\..*) replace with: $2_-_$3$5 

Note: this assumes that you are including the file extension in the renaming process, and makes sure you retain that extension, in case you also have .ogg files or whatever. If your tool is not including the extension in the renaming process, remove the last "(\..*)" from the search, and the last $5 from the replace.

Your name now looks like: 1_-_Michael_Jackson_-_Wanna_Be_Startin'_Something.mp3

SECOND: now replace the first occurence of "_._" by " " and the second by " - ":

search for: (.*?)_-_(.*?)_-_(.*)(\..*) replace with: $1 $2 - $3$4 

Note: Again, if your tool is not including the file extension in the process, remove the last "(\..*)" from the search and the last $4 from the replace.

Your name now looks like: 1 Michael_Jackson - Wanna_Be_Startin'_Something.mp3

THIRD AND LAST: Simply replace "_" by " ".

Your name now looks like: 1 Michael Jackson - Wanna Be Startin' Something.mp3

Good luck!

/edit: quite some precision required to make sure all these underscores are correctly displayed in this post :)

/edit 2: Afterthought. You may also want to pad the track numbers below 10 (i.e. 0-9) with a 0, so you get 01, 02, ..., 09, 10, 11 etc.. this makes sorting much easier and hugely increases chances for things like phones or MP3 players to play your tracks in the correct order. For that:

Search for: (^[0-9] ) Replace with: 0$1 
Это выглядит как отличный способ сделать это. Я попробую это сегодня вечером и дам вам знать. Я установил TC на своей машине здесь, но у меня нет доступа к файлам, которые мне нужно изменить, кроме как через FTP, и я не хочу проверять свою пропускную способность с такой сложной задачей. Я должен добавить, что существующие имена файлов в настоящее время заполнены двумя цифрами, поэтому я не ожидаю, что мне нужно будет добавлять заполнение, если что-то в более раннем регулярном выражении не было настроено для его удаления, но я не смог (хотя и с мои ограниченные знания) увидеть что-нибудь, что, казалось бы, предполагает это. LincM 9 лет назад 0
Все мои регулярные выражения здесь совместимы с именами с 0 дополнениями и оставят их нетронутыми. (([0-9] +) _): поиск ((одна или несколько цифр) с последующим подчеркиванием). SadBunny 9 лет назад 0
0
Xen2050

My first instinct is to not try to write a program or script to do this, but to use a ready-made mp3 renaming program to do it for you. There are different ones available (of varying quality) for different OS's.

Or if you're gung-ho on the renaming idea, you could use gnu tools (available in linux/unix/mac, or Cygwin) like sed or awk, or tr & cut & variables in a bash script... you'll need a standard way to separate out the fields (song, artist, track) in your filenames, if you're using a variable number of spaces in between them, with no set field separator, that would be tricky.

Here's a very very quick preliminary awk line that separates the incoming string (after _ have been translated into spaces) and prints them out in a different order, you'll have to figure out keeping the "tracknumber" at the start yourself:

$ jackstring="tracknumber_artistname-songname_MP3COLLECTION.mp3" $ echo $jackstring tracknumber_artistname-songname_MP3COLLECTION.mp3 $ echo "$jackstring"|tr -s "_" " "|awk -F'[-.]' '' songname MP3COLLECTION-tracknumber artistname.mp3 

Похожие вопросы