Deleting Files in R based on their Names

I am working with the R programming language.

I recently learned how to delete a file having a specific name from the working directory:

#Define the file name that will be deleted
fn <- "foo.txt"

#Check its existence
if (file.exists(fn)) {
    #Delete file if it exists
    file.remove(fn)
}

[1] TRUE

My Question: Is it possible to delete files based on whether the file name contains a specific combination of letters (i.e. LIKE 'fo%' )? This way, all files in the working directory starting with the letters "fo" will be deleted.

What I tried so far:

I thought of a way where I could first create a list of all files in the working directory that I want to delete based on their names:

# create list of all files in working directory 
a = getwd()
path.to.csv <- a
files<-list.files(path.to.csv)
my_list = print(files)  ## list all files in path

#identify files that match the condition
to_be_deleted = my_list[grepl("fo",unlist(my_list))]

Then, I tried to deleted this file using the command used earlier:

if (file.exists(to_be_deleted)) {
    #Delete file if it exists
    file.remove(to_be_deleted)
}

This returned the following message:

[1] TRUE TRUE TRUE TRUE TRUE TRUE
Warning message:
In if (file.exists(to_be_deleted)) { :
  the condition has length > 1 and only the first element will be used

Does anyone know if I have done this correctly? Suppose if there were multiple files in the working directory where the names of these files started with "fo" - would all of these files have been deleted? Or only the first file in this list?

Can someone please show me how to do this correctly?

Thanks!

The list.files() function has a pattern argument that you can use to select files. For example, to delete all files whose name ends in csv from the current directory

FILES <- list.files(pattern = "csv$")
file.remove(FILES)
1 Like

@ FJCC : thank you for your reply! Would this code above remove all files that contain the letters "csv"?

For instance, would the following files be deleted?

"my_csv.txt"

"my_txt.csv"

Using the code you provided:

FILES <- list.files(pattern = "csv$")
file.remove(FILES)

Would both of these files be deleted?

Thank you so much!

As written, the code looks for files whose name ends with csv. The $ represents the end of the name. If you remove the $, the function will find files with csv anywhere in the name. The pattern argument is a regular expression. Learning regular expressions is worth the trouble.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.