1

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?

1 Answer 1

2

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()

2
  • Awesome, that worked like a charm. Can you please explain the logic behind file.rename? It never occurred to me! Thanks once again.
    – VGu
    Oct 29, 2020 at 0:26
  • 1
    It's just two parameters, old name, new name. As long as you put the paths together, you can move a file to whatever existing folder you like. Renaming a file is basically the same thing as moving it.
    – MrFlick
    Oct 29, 2020 at 0:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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