Reputation: 179
I have a csv list of txt files (without the full path, looking like so: filea.txt) that are located in multiple subdirectories. I would like to copy paste all those files in a single directory.
To make matter more difficult, this csv list of txt files does not have a repeatable pattern. The names in this list will have to be matched against a list of all the txt files in the directory.
Would anybody know how to do this ?
Here's my attempt:
# Target and source
source <- "C:/Users/blue/Desktop/A"
target <- "C:/Users/blue/Desktop/B"
# List of all txt files in main directory
all.files <- list.files(path = source,
recursive = TRUE,
pattern = ".txt",
full.names = TRUE)
# List of specific txt files to extract
extract.files <- read.csv(paste0(source, "/extract.csv"), head = FALSE, sep=",")
# Somehow match list of specific files with list of all txt files here
# Function to copy paste
my.file.rename <- function(from, to) {
todir <- dirname(to)
if (!isTRUE(file.info(todir)$isdir)) dir.create(todir, recursive=TRUE)
file.copy(from = from, to = to)
}
# Copy paste
my.file.rename(from = source,to = target)
Upvotes: 1
Views: 287
Reputation: 8072
You don't need a custom function.
# Target and source
source <- "C:/Users/blue/Desktop/A"
target <- "C:/Users/blue/Desktop/B"
# List of all txt files in main directory
all.files <- list.files(path = source,
recursive = TRUE,
pattern = ".txt",
full.names = TRUE)
# List of specific txt files to extract
extract.files <- read.csv(paste0(source, "/extract.csv"), head = FALSE, sep=",")
toCopy <- all.files[which(basename(all.files) %in% unlist(extract.files))]
file.copy(toCopy, target)
Upvotes: 1