Search code examples
rfile-copyingname-matching

Match partial file name to full file name


I have file list named in the following way

csv_files<-list.files(path, pattern =‘.csv’)

1001_2017_01_02#19_30_24.csv 1002_2018_03_01#20_30_54.csv...

Format is essentially: id _year_month_day#hour_min_sec.csv.

I have striped the ID and date from the file name in order to sort using the neardate function. Eventually I have a data frame containing the prefix 1001_2017_01_02 and not the full file name. Essentially I want to match the partial file name from the final data frame to the full file name then copy the matching files to a new path.

Any comments would be helpful thanks.


Solution

  • The code below is untested, since I don't have those files on my disk, nor I have a new path.
    I would do something along the lines of

    csv_files <- c("1001_2017_01_02#19_30_24.csv", "1002_2018_03_01#20_30_54.csv")
    dat <- data.frame(prefix = c("1001_2017_01_02", "1002_2018_03_01"))
    
    lapply(dat$prefix, function(x) {
        fl <- csv_files[grep(x, csv_files)]
        file.copy(from = fl, to = newpath)
    })