Skip to content

Instantly share code, notes, and snippets.

@tjmahr
Created September 16, 2024 20:00
Show Gist options
  • Save tjmahr/50b70722ebb1b7bad5bfb37ca6b644d2 to your computer and use it in GitHub Desktop.
Save tjmahr/50b70722ebb1b7bad5bfb37ca6b644d2 to your computer and use it in GitHub Desktop.
# 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment