LH01
LH01

Reputation: 39

Same but Different! Renaming Multiple Files using R

I am new to R coding and I am in the process of trying to write code in order to rename a series of pdf files in the same folder:

Letter131.pdf
Letter132.pdf
Letter133.pdf 

There are likely to be ~1000 files that I will eventually need to rename.

I would like to rename these files so that they have an "_" between the 2nd and 3rd digits:

Letter13_1.pdf
Letter13_2.pdf
Letter13_3.pdf

I have found various answers on renaming multiple files and unfortunately I am unable to re-jig them to work.

One example I have come up with is this:

file_names <- list.files(pattern="*.pdf")
sapply(file_names, FUN = function(eachPath){
  file.rename(from = eachPath, to = sub(pattern = "Letter13$.pdf", paste0("Letter13_$"), 1:3, eachPath))
})

Is anyone able to help me out on this?

Upvotes: 3

Views: 225

Answers (1)

agstudy
agstudy

Reputation: 121608

file.rename is vectorized , no need to use a loop here:

## insert _ using grouping pattern
TO <- sub('(.*)([0-9][.]pdf)','\\1_\\2',file_names)
## rename a vector 
file.rename(file_names , TO)

Example of pattern use :

file_names <- c("Letter131.pdf","Letter132.pdf","Letter133.pdf")
sub('(.*)([0-9][.]pdf)','\\1_\\2',file_names)  
## [1] "Letter13_1.pdf" "Letter13_2.pdf" "Letter13_3.pdf"

Upvotes: 3

Related Questions