Automatically Delete Files/Folders

旧街凉风 提交于 2019-11-26 18:51:36
joran

Maybe you're just looking for a combination of file.remove and list.files? Maybe something like:

do.call(file.remove, list(list.files("C:/Temp", full.names = TRUE)))

And I guess you can filter the list of files down to those whose names match a certain pattern using grep or grepl, no?

For all files in a known path you can:

unlink("path/*")
dir_to_clean <- tempdir() #or wherever

#create some junk to test it with
file.create(file.path(
  dir_to_clean, 
  paste("test", 1:5, "txt", sep = ".")
))

#Now remove them (no need for messing about with do.call)
file.remove(dir(  
  dir_to_clean, 
  pattern = "^test\\.[0-9]\\.txt$", 
  full.names = TRUE
))

You can also use unlink as an alternative to file.remove.

Using a combination of dir and grep this isn't too bad. This could probably be turned into a function that also tells you which files are to be deleted and gives you a chance to abort if it's not what you expected.

# Which directory?
mydir <- "C:/Test"
# What phrase do you want contained in
# the files to be deleted?
deletephrase <- "deleteme"

# Look at directory
dir(mydir)
# Figure out which files should be deleted
id <- grep(deletephrase, dir(mydir))
# Get the full path of the files to be deleted
todelete <- dir(mydir, full.names = TRUE)[id]
# BALEETED
unlink(todelete)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!