### This function can be used to merge in a single folders, files that are ### placed in multiple subfolders. ### from: folder which contains a bunch of sub-folders ### to: folder where all the files are going to be merged ### patternFromDir: pattern to select only a subset of all the sub-folders ### patternFiles: operate the merging only on a particular set of files ### quiet: if FALSE ask for confirmation before merging files in destination folder ### Example: ### mergeFilesInFolder(getwd(), "../mergedPhotos", patternFromDir="[0-9]", patternFiles="JPG|NEF", quiet=T) mergeFilesInFolder <- function(from, to, patternFromDir="[0-9]", patternFiles="JPG|NEF", quiet=F) { listDirFrom <- list.files(from, patternFromDir) listDirFrom <- listDirFrom[file.info(listDirFrom)$isdir] if(substr(from, nchar(from), nchar(from)) == "/") substr(from, nchar(from), nchar(from)) <- "" if(substr(to, nchar(to), nchar(to)) == "/") substr(to, nchar(to), nchar(to)) <- "" for(eachDir in listDirFrom) { fromDir <- paste(from, eachDir, sep="/") listFiles <- list.files(fromDir, patternFiles) listFilesFrom <- paste(fromDir, listFiles, sep="/") destFiles <- paste(to, listFiles, sep="/") filesToMove <- cbind(listFilesFrom, destFiles) if(!quiet) { print(filesToMove) prt <- readline("Proceed? (yes/no) \n") if(! identical(prt, "yes") ) stop("Stopped by user.") } if(any(file.exists(destFiles))) stop("destination file already exist") #browser() rslt <- apply(filesToMove, 1, function(x) file.copy(x[1], x[2])) if(!all(rslt)) warning("Something went wrong in folder ", eachDir) } invisible() }