简体   繁体   中英

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?

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM