Search code examples
rfile-copying

How to move one file from a directory to another no R using just a part of the file name?


I'm trying to find a code that moves a file from one directory to another using only a part of the name, this is because the file is generated daily and only a part of the file name is constant (the rest varies each day without a defined pattern).

An example of one file I want to move is this (using list.files command):

> list.files("V:/evfilesce9i9/apps9/vbe9/dep4/KFTP/KFTP001D_FicherosCeca", "EnviaCecaReservedLimit")
[1] "EnviaCecaReservedLimit_0239_PRO_201711172000331.csv"

I tried file.rename() but I am not able to find the way to use only a partial string of the name to move it with this command.

clarification: I'm aiming just to MOVE the file from one directory to another, not to rename it, I want the name of the file to be the same in the destination directory as it is in the original directory

Could anyone help me?


Solution

  • I hope this is what you need. (use a test directory and test files for testing)

    setwd("C:/currentdir/")
    
    newdir <- "C:/newdir"
    
    currentdir <- getwd()
    
    files <- list.files(path = currentdir, full.names = TRUE)
    
    files_new <- gsub(dirname(files[1]), newdir, files)
    
    for (i in 1:length(files)) {
    
      file.copy(files[i], files_new[i])
    
    }