Here is a function that does what you ask for.
The main problem is to assemble the new names from the old names' path and file extension. This is done with functions
- 包装
base
中的basename
和dirname
;
- 包装
tools
中的file_ext
和file_path_sans_ext
.
连续的数字是由seq_along
产生的.然后paste0
、sprintf
和file.path
把所有的东西放在一起.
如果希望所有数字的位数相同,请将fmt_string
字符串的格式部分更改为"%04d.%s"
.
file_rename_custom <- function(path, pattern, prefix = "Animals") {
files_vec <- list.files(path = path, pattern = pattern, full.names = TRUE)
ext <- tools::file_ext(files_vec)
fname <- files_vec |>
basename() |>
tools::file_path_sans_ext()
fmt_string <- paste0(prefix, "%d.%s")
new_name <- sprintf(fmt_string, seq_along(fname), ext)
new_name <- file.path(dirname(files_vec), new_name)
file.rename(files_vec, new_name)
}
working_directory <- getwd()
wd1 <- file.path(working_directory, "animals/photos")
wd2 <- file.path(working_directory, "animals")
dir(wd1)
# [1] "Cat.txt" "Chiken.txt" "Moose.txt"
file_rename_custom(wd1, "\\.txt")
# [1] TRUE TRUE TRUE
dir(wd1)
# [1] "Animals1.txt" "Animals2.txt" "Animals3.txt"
dir(wd2)
# [1] "Cat.txt" "Chiken.txt" "Moose.txt" "photos"
file_rename_custom(wd2, "\\.txt")
# [1] TRUE TRUE TRUE
dir(wd2)
# [1] "Animals1.txt" "Animals2.txt" "Animals3.txt" "photos"