相同但不同!使用R重命名多个文件

时间:2021-04-19 20:33:14

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:

我是R编码的新手,我正在尝试编写代码,以便在同一个文件夹中重命名一系列pdf文件:

Letter131.pdf
Letter132.pdf
Letter133.pdf 

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

我最终可能需要重命名大约1000个文件。

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

我想重新命名这些文件,使它们在2位数和3位数之间有一个“_”:

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.

我找到了关于重命名多个文件的各种答案,不幸的是,我无法重新对它们进行jig。

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?

有人能帮我解决这个问题吗?

1 个解决方案

#1


3  

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"

#1


3  

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"