Search code examples
rfile-transfer

Can R be utilized to automate file migration?


Based on some of the responses, I've edited the original post to make it more specific :)

The issue - I would like to figure out how to automate file migration.

This is an excerpt of the file structure in directory ".../test"

  • 011_433

  • 9087_345

  • new_files

Folders 011_433 and 9087_345 have files in them that have some string patterns, like for example files having 'B_14' or 'B_15' in the file name. The files are interspersed through the folders, so files that have 'B_14' don't reside in just one folder (same is true for files with other patterns). Folder new_files is where I would like the files to migrate to, such that they reside in folders named based on their pattern, such as:

Directory ".../test/new_files" would have subdirectories like:

  • B_14

  • B_15

where each folder would contain files with names that have a string pattern matching the folder name.

This is what I've done so far, which works, but I am really at a loss as to how to automate it beyond this, since there isn't any rhyme or reason to the file pattern names.

library(filesstrings)

path <- "C:/my_directory/test/"
setwd(path)

#get a list of all files in test directory sub folders that match a specific #string pattern
B_14_ <- list.files(path, pattern = "_B-14", recursive = TRUE) 

#move all the files from test into their respective folder under 'new_files'
file.move(B_14_, "C:/my_directory/test/new_files/B_14"


#repeat for the next pattern....
B_15_ <- list.files(path, pattern = "_B-15", recursive = TRUE)
file.move(B_15_, "C:/my_directory/test/new_files/B_15"

#etc.

My question is can I automate it any more? If I had a list of all the string patterns could I somehow incorporate that in?

Thanks for the help!


Solution

  • Sure, here's one more level of abstraction:

    path <- "C:/my_directory/test/"
    setwd(path)
    patts = c("B-14", "B-15")
    dirs = sub(pattern = "-", replacement = "_", x = patts, fixed = TRUE)
    
    for (i in seq_along(patts)) {
      files <- list.files(path, pattern = paste0("_", patts[i]), recursive = TRUE) 
      file.move(files, paste0("C:/my_directory/test/new_files/", dirs[i]"))
    }