Search code examples
rregexstringmax

Get maximum value in list of filenames


I have a list of filenames with the general title

a_file_name_1
a_file_name_34
a_file_name_452
new_data_2018.csv

I would like to rename the new_data_2018.csv file so that its numerical end is one greater than the largest pre-existing file in the folder.

So far I have

#list files in directory
list_files_names <- list.files(directory_2018)

#capture largest suffix
largest_value <-
new_largest_value <- largest_value + 1

# rename file
file.rename("new_data_2018.csv", paste0('a_file_name_', new_largest_value)

My question is how I can I collect the existing filenames in such a way that returns the largest suffix. I imagine that it might have something to do with regular expressions for which the following regex might be useful [0-9]*$.


Solution

  • You can parse number, select the biggest one and then add +1:

    files <- c("a_file_name_1",
    "a_file_name_34",
    "a_file_name_452")
    
    largest_value <- as.numeric(gsub("\\D", "", files))
    new_largest_value <- max(largest_value) + 1
    

    If you have other numbers in your files, you can use some regex or just split it on underscores and then transform the last element into numbers:

    files <- c("a_file_name_2019_1",
    "a_file_name_2019_34",
    "a_file_name_2019_452")
    
    largest_value <- as.numeric(gsub("\\D", "", sapply(strsplit(files, "_", fixed = TRUE), tail, 1)))
    new_largest_value <- max(largest_value) + 1
    

    Or using regex:

    largest_value <- as.numeric(sub(".*\\_", "", files))
    new_largest_value <- max(largest_value) + 1