LMontef
LMontef

Reputation: 41

renaming file based on folder names with R

I have a folder Tmin which contains 18 folders. Each of the 18 folders contains hundreds of file. I would like to create a program with R that allow to add the name of the folder files for each file. I do not want to rename each of the file with a different name, I only want to add the folder name at the beginning of the file name. I am new in R and in programming. I was not able to have a batch function that can repeat the operation for each folder. You can find attached two pictures, which show what I would like to obtain.

For example, the file called "name_date.tiff" contained in the folder "MACA_Miroc" will become "MACA_Miroc_name_date.tiff". Moreover, I would like to repeat the operation automatically for each folder. Thanks in advance for any help!

Wanted situation and organization of my folders and file

Upvotes: 1

Views: 4125

Answers (2)

Gautam
Gautam

Reputation: 2753

This ought to work:

mydir <- getwd()  
primary_folder <- "C:/Users/Desktop/Test_Data/"
subfolders <- grep("*MACA*", list.dirs(primary_folder, full.names = T, recursive = F), 
                   value = T)

renameFunc <- function(z){
  setwd(z)
  fnames <- dir(recursive = F, pattern= ".tiff|.csv")
  addname <- substr(z, nchar(primary_folder)+2, nchar(z))

  lapply(fnames, function(current_name){
    #Regex to get extension, may need to addd $ sign to signify end of file name
    ptrn <- ".*\\.([a-zA-Z]{2,4})" 
    extension <- regmatches(current_name, regexec(ptrn, current_name))[[1]][2]
    no_extension <- gsub(paste(".",extension, sep = ""), "", current_name)
    new_name <- paste(gsub("_"," ", no_extension), " ", addname, ".", extension, sep = "")
    file.rename(current_name, new_name)
  })
}

lapply(subfolders, readFunc)

setwd(mydir)

I think if you're not in the directory where you want to change file names, you must specify the full name. Changing the working directory was a quick way but you could use full names (using regular expressions to get the correct from and to values for file.rename()). I got some errors at one poing when I was not in the directory where I wanted to change the name.

I feel this allows more control over which folders you want to change the names in since incorrect operation can be very messy. You may also want to skip some file extensions or subfolders etc.

Upvotes: 1

Terru_theTerror
Terru_theTerror

Reputation: 5017

Your path folder

folder<-"C:/path/example/"

Extract files list

files<-list.files(folder)

Extract folder name

folder_name<-unlist(strsplit(folder,"/"))[length(unlist(strsplit(folder,"/")))]

Rename all files

file.rename(from = paste0(folder,files),to = paste0(folder,folder_name,"_",files))

Upvotes: 0

Related Questions