Search code examples
rfilemp3rename

R - Renaming files in directory


I have multiple mp3 files that I want to rename to organize them. Most of them have a similar format: the number 0, followed by a number (1:9), a space, and then the mp3 file name. They look something like this:

head(files)
[1] "01 50 Cent - Candy Shop.mp3"                
[2] "01 50 Cent - Fresh '83.mp3"                 
[3] "01 Akon ft Eminem - Smack That.mp3"         
[4] "01 Akon ft Snoop Dog - I Wanna Love You.mp3"
[5] "01 Aldo Ranks - Baila.mp3"                  
[6] "01 Aldo Ranks - El Alicate.mp3"  

or

head(files[1098:1102])
[1] "1-01 Spragga Benz - She Nuh Ready Yet.mp3"          
[2] "1-01 Tal Bachman - Darker Side Of Blue.mp3"         
[3] "1-01 When Love Takes Over (feat. Kelly Rowland).mp3"
[4] "1-02 Big Boy - Voz Sensual.m4a"                     
[5] "1-02 Come Out And See.mp3"  

For simplicity, my working directory is the folder containing these files. What would be an efficient way to rename this files? Probably using a regex such as substr, grep, or some other? Should I write a function?

I tried to store the file names in a variable called files, but it's not efficient because changes to elements in are not reflected in my working directory.

Any suggestions>


Solution

  • I'm not a regex expert, far from it, but this one is simple.

    files <- 
    c("01 50 Cent - Candy Shop.mp3", "01 50 Cent - Fresh 83.mp3", 
    "01 Akon ft Eminem - Smack That.mp3", "01 Akon ft Snoop Dog - I Wanna Love You.mp3", 
    "01 Aldo Ranks - Baila.mp3", "01 Aldo Ranks - El Alicate.mp3"
    )
    
    new_names <- sub("^0[[:digit:]] ", "", files)
    new_names
    

    Then, to actually rename them use file.rename.

    file.rename(from = files, to = new_names)