Search code examples
rdirectorybatch-processingcopy-paste

Copy-paste files to folders that have matching names using R


I am trying to copy files to various folders that have matching filenames.

Here's an extract of the filenames:

20201026_ABCD.txt
20201026_XYZ.txt
20201027_ABCD.txt
20201027_POR.txt
20201028_ABCD.txt
20201028_PQR.txt

I want to create folders that have just the date components from the files above. I have managed to get that far based on the code below:

setwd("C:/Projects/TEST")
        
library(stringr)
        
filenames<-list.files(path = "C:/Projects/TEST", pattern = NULL)
        
#create a variable that contains all the desired filenames
foldernames.unique<-unique(str_extract(filenames,"[0-9]{1,8}"))
    
#create folders based on this variable
foldernames.unique<-paste("dates/",foldernames.unique,sep='')
lapply(foldernames.unique,dir.create,recursive = TRUE)

Now, how do I copy 20201026_ABCD.txt and 20201026_XYZ.txt to the folder 20201026, so on and so forth?


Solution

  • Now you just need to use file.rename to move the files. First i'll change things a bit to capture the non-unique folder names so I don't have to recauclate them. How about this

    srcfolder <- "C:/Projects/TEST"
    filenames <- list.files(path = srcfolder, pattern = NULL)
            
    #create a variable that contains the desired foldername for each file
    foldernames <- file.path("dates", str_extract(filenames,"[0-9]{1,8}"))
    foldernames.unique <- unique(foldernames)
        
    #create folders based on unique values of variable
    lapply(foldernames.unique, dir.create, recursive = TRUE)
    
    # Now move files
    file.rename(file.path(srcfolder, filenames), file.path(foldernames, filenames))
    

    We just build the file names with file.path which is a bit more robust than paste()