DaphFab
DaphFab

Reputation: 73

Match filenames in a folder with a list of filenames in R

I have a list of filenames in text format, meaning just the filenames and not the physical files in a folder. FOR example....

   ECGVW103899_wholecaseRRiQTi.rr
   ECGVW104077_wholecaseRRiQTi.rr
   ECGVW104081_wholecaseRRiQTi.rr
   ECGVW104121_wholecaseRRiQTi.rr
   ECGVW104182_wholecaseRRiQTi.rr
   .
   .
   .

I have a folder with a list of files. These files include the names in the list that I indicated above(and some additional files). I need to separate the additional files in the folder by moving it to a separate folder. Any suggestions?

Upvotes: 1

Views: 277

Answers (1)

Matt Jewett
Matt Jewett

Reputation: 3369

Something like this may give you the result you're looking for.

files.to.keep <- c("ECGVW103899_wholecaseRRiQTi.rr",
                   "ECGVW104077_wholecaseRRiQTi.rr",
                   "ECGVW104081_wholecaseRRiQTi.rr",
                   "ECGVW104121_wholecaseRRiQTi.rr",
                   "ECGVW104182_wholecaseRRiQTi.rr")

source.path <- # Path to file source folder
destination.path <- # Path to file destination folder

# Create destination folder if it does not exist
ifelse(!dir.exists(destination.path), dir.create(destination.path), FALSE)

# Get list of files in source folder
filenames <- list.files(source.path)

# Move files that are not in files.to.keep to the destination folder
lapply(filenames, function(x) 
                    if(!(x %in% files.to.keep))
                      {file.rename(from = file.path(source.path,x),to = file.path(destination.path,x))})

Upvotes: 1

Related Questions