#' Find and move files in sequence
#'
#' @export
#' @note Updated 2022-09-08.
#'
#' @param sourceDir `character(1)`.
#' Source directory of files to rename.
#'
#' @param targetDir `character(1)`.
#' Target directory of files to rename.
#'
#' @param pattern `character(1)` or `NULL`.
#' File matching pattern. Refer to `list.files()` for details.
#'
#' @return `character`.
#' File paths of renamed files.
#'
#' @examples
#' testDir <- AcidBase::tempdir2()
#' sourceDir <- file.path(testDir, "source")
#' targetDir <- file.path(testDir, "target")
#' paths <- c(sourceDir, targetDir)
#' invisible(lapply(X = paths, FUN = dir.create, recursive = TRUE))
#' invisible(file.create(
#' file.path(
#' sourceDir,
#' paste0(
#' c("aaa", "bbb", "ccc"),
#' ".txt"
#' )
#' )
#' ))
#' print(sort(list.files(
#' path = sourceDir,
#' full.names = FALSE,
#' recursive = FALSE
#' )))
#' out <- findAndMoveInSequence(
#' sourceDir = sourceDir,
#' targetDir = targetDir
#' )
#' print(out)
#' print(sort(list.files(
#' path = targetDir,
#' full.names = FALSE,
#' recursive = FALSE
#' )))
#' AcidBase::unlink2(testDir)
findAndMoveInSequence <-
function(sourceDir,
targetDir,
pattern = NULL) {
assert(
requireNamespaces("syntactic"),
isADir(sourceDir),
isADir(targetDir),
!identical(sourceDir, targetDir),
isString(pattern, nullOk = TRUE)
)
sourceFiles <- sort(list.files(
path = sourceDir,
pattern = pattern,
all.files = FALSE,
full.names = TRUE,
recursive = TRUE,
include.dirs = FALSE
))
targetFiles <- file.path(
targetDir,
paste0(
strtrim(
syntactic::kebabCase(
paste(
syntactic::autopadZeros(seq_along(sourceFiles)),
basenameSansExt(sourceFiles),
sep = "-"
),
prefix = FALSE
),
width = 100L
),
".", fileExt(sourceFiles)
)
)
assert(identical(length(sourceFiles), length(targetFiles)))
invisible(Map(
from = sourceFiles,
to = targetFiles,
f = function(from, to) {
alert(sprintf("Renaming {.file %s} to {.file %s}.", from, to))
file.rename(from = from, to = to)
}
))
alertInfo(sprintf(
"Successfully renamed %d %s.",
length(sourceFiles),
ngettext(
n = length(sourceFiles),
msg1 = "file",
msg2 = "files"
)
))
invisible(targetFiles)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.