Copying specific files from multiple sub-directories into a single folder in R

我们两清 提交于 2019-12-02 05:15:02
parent.folder <- "C:/Desktop/dir"
files <- list.files(path = parent.folder, full.names = T, recursive = T, include.dirs = T)

After this you need to select the relevant files:

files <- files[grep("wang\\.tax\\.sum", files)]

(Notice double-escapes before dots: \\. - dot has a special meaning for grep.)

Or you could do this with pattern argument to list.files in one step:

files <- list.files(path = parent.folder, full.names = T, recursive = T, include.dirs = T, pattern = "wang\\.tax\\.sum")

Creating new dir:

dir.create("taxsum", recursive = T)

Now you need to create new filenames:

newnames <- paste0("taxsum/", gsub("/|:", "_", files))
# replace "special" characters with underscore
# so that your file names will be different and contain the 
# original path

# alternatively, if you know that file names will be different:
newnames <- paste0("taxsum/", basename(files))

And now you can use mapply to copy (the same can be done with for with a little extra effort):

mapply(file.copy, from=files, to=newnames)

Your my_dirs already contains full file names, and creating the files variable is not necessary.

parent.folder <- "Desktop"
ext <- ".jpg"                 # Wanted file extension

my_dirs <- list.files(path = parent.folder, 
    full.names = TRUE, recursive = TRUE, include.dirs = TRUE)

dir.create("Desktop/temp", recursive = TRUE)

n <- sapply(my_dirs[grep(ext, my_dirs)], 
    FUN=function(x) file.copy(from = x, to = "Desktop/temp/"))

message(paste("Number of files in", parent.folder, "with", ext, ":", length(n), 
    "(successully copied:", round(sum(n)/length(n)*100, 0), "%).")) 

# Number of files in Desktop with .jpg : 4 (successully copied: 100 %).

The variable n will contain a named logical vector, which you can explore in case of any problems in copying the files.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!