# Rename files with str_replace()
file_replace_name <- function(path, ..., .dry_run = FALSE) {
.file_move2(path, stringr::str_replace, ..., .dry_run = .dry_run)
}
preview_file_replace_name <- function(path, ...) {
file_replace_name(path, ..., .dry_run = TRUE)
invisible(path)
}
# Apply a renaming function then rename files
.file_move2 <- function(path, f, ..., .dry_run = FALSE) {
new_path <- f(path, ...)
changed <- path != new_path
stopifnot(length(unique(path)) == length(unique(new_path)))
if (.dry_run) {
changes <- sprintf(
"\n- %s -> %s",
basename(path)[changed],
basename(new_path)[changed]
)
message("Plan: ", changes)
invisible(path)
} else {
fs::file_move(path[changed], new_path[changed])
invisible(new_path)
}
}
files <- c("a-1.txt", "aa-2.txt", "a-3.txt")
file.create(files)
#> [1] TRUE TRUE TRUE
files |>
file_replace_name("a+", "alpha", .dry_run = TRUE)
#> Plan:
#> - a-1.txt -> alpha-1.txt
#> - aa-2.txt -> alpha-2.txt
#> - a-3.txt -> alpha-3.txt
files |>
file_replace_name("a+", "alpha")
list.files()
#> [1] "alpha-1.txt" "alpha-2.txt"
#> [3] "alpha-3.txt" "smoky-moose_reprex.R"
#> [5] "smoky-moose_reprex.spin.R" "smoky-moose_reprex.spin.Rmd"
Created on 2024-09-16 with reprex v2.1.1