0

Is there a way to rename multiple files, using some template written for example in the txt file? I need to replace some specific words with some other words in the bunch of files. I've got, say 1000+ files named like this:

file1-music-mozart-directed-by-karajan-youtube.mp3
file2-music-beethoven-symphonies-youtube.mp3

and I want to capitalize the words "Mozart" and "Karajan", and replace "youtube" with "YT". Also I'd like to add some new rules (patterns) to the forementioned text file in the future when I need it. But I don't insist on the txt file, it's just my humble idea...

  • does all 1000+ files contains mozart, karajan and youtube string in it? – Rahul Jun 10 '16 at 15:51
2
$ ls -1
file1-music-mozart-directed-by-karajan-youtube.mp3
file2-music-beethoven-symphonies-youtube.mp3

$ rename -v -e 's/youtube/YT/;
    s/(-music-)([[:alpha:]])/$1 . uc $2/e;
    s/(-directed-by-)([[:alpha:]])/$1 . uc $2/e' *
file1-music-mozart-directed-by-karajan-youtube.mp3 renamed as file1-music-Mozart-directed-by-Karajan-YT.mp3
file2-music-beethoven-symphonies-youtube.mp3 renamed as file2-music-Beethoven-symphonies-YT.mp3

$ ls -1
file1-music-Mozart-directed-by-Karajan-YT.mp3
file2-music-Beethoven-symphonies-YT.mp3

the perl code used by rename does the following:

  1. replaces youtube with YT
  2. capitalises the first letter after -music-
  3. capitalises the first letter after -directed-by-

This, obviously, matches more than just mozart and karazan. It uppercases the names of any composer or artist, and any director.

The last two use the /e modifier to the search and replace operator, which tells perl to evaluate the right-hand-side (the replacement) as a perl expression, so I can use perl functions like uc (uppercase).

If you only want to uppercase the first letter of a smallish set of words, use something like this instead:

$ rename -v -e 's/youtube/YT/;
                s/(mozart|karajan)/ucfirst($1)/eg;' *
file1-music-mozart-directed-by-karajan-youtube.mp3 renamed as file1-music-Mozart-directed-by-Karajan-YT.mp3
file2-music-beethoven-symphonies-youtube.mp3 renamed as file2-music-beethoven-symphonies-YT.mp3

$ ls -1
file1-music-Mozart-directed-by-Karajan-YT.mp3
file2-music-beethoven-symphonies-YT.mp3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.