Joachim Schork
Joachim Schork

Reputation: 2147

Duplicate/Copy same file N times

I have an R file that is stored in a directory on my computer. I would like to create 10 duplicates of this R file in an automatized way. The 10 duplicates of this R file should be stored in the same directory and each of them should have a different file name.

Example:

My working directory:

getwd()
# [1] "D:/Example Directory"

With the dir function, I can extract the names of all files that are stored in this directory:

path <- getwd()
dir(path)
# "1.R"

The only file in this directory is the R file 1.R. I would like to duplicate this R file 10 times. The duplicates should be called 2.R, 3.R, 4.R and so on.

This could be easily done with a manually conducted copy/paste. However, since I have to duplicate the file many times, I'm looking for an automatized way in R.

Question: How could I duplicate this R file in an automatized way?

Upvotes: 3

Views: 2196

Answers (1)

pogibas
pogibas

Reputation: 28369

You can use file.copy function that needs original file name as first argument and accepts vector of wanted file names as second argument.

file.copy(dir(getwd()), paste0(2:10, ".R"))

PS: Make sure that in current directory there's only one file in the beginning.


Or you can use a safe solution with list.files and file.exists:

nFiles <- 10
myFile <- list.files(pattern = "\\d.R")
for(i in seq_len(nFiles)) {
   wantedFile <- sub("\\d", i, myFile)
   if (!file.exists(wantedFile)) {
      file.copy(myFile, wantedFile)
   }
}

Upvotes: 5

Related Questions