Skip to content

Instantly share code, notes, and snippets.

@chris-prener
Last active February 17, 2019 01:45
Show Gist options
  • Save chris-prener/1bf67a8788593391faae063ef03e8aa9 to your computer and use it in GitHub Desktop.
Save chris-prener/1bf67a8788593391faae063ef03e8aa9 to your computer and use it in GitHub Desktop.
Rename files using purrr+stringr+fs
# These two functions address a common problem in my work - files named "monthYYYY.CSV.html" -
# e.g. "August2018.CSV.html". The prep_dir() function creates a vector of filenames in a given directory
# and then iterates over each using purrr::map(). The map() function calls our second function, edit_filename().
# For each time it is called, edit_filename() uses the magic of stringr and fs (okay, it isn't really magic)
# to rename the file appropriately.
# dependencies:
# install.packages(c("fs", "magrittr", "purrr", "stringr"))
# include in script:
library(magrittr)
# iterate over filenames in directory
prep_dir <- function(path){
# create vector of filenames
files <- list.files(path)
# iterate over each filename, renaming it and coverting to lowercase
files %>%
split(files) %>%
purrr::map(~edit_filename(path = path, file = .x))
# create vector of new filenames
newFiles <- list.files(path)
# create output
out <- list(
original = files,
new = newFiles
)
# return output
return(out)
}
# edit an individual filename
edit_filename <- function(path, file){
# only edit files that end with .html
if (stringr::str_detect(file, pattern = ".html$") == TRUE){
# construct a new file name that is all lower case, removes .html from end
newFile <- tolower(stringr::str_replace(file, pattern = ".html$", replacement = ""))
# create new file paths, adding a forward slash between path and filename if necessary
if (stringr::str_detect(path, pattern = "/$") == FALSE){
filePath <- stringr::str_c(path, "/", file)
newPath <- stringr::str_c(path, "/", newFile)
} else {
filePath <- stringr::str_c(path, file)
newPath <- stringr::str_c(path, newFile)
}
# rename file
fs::file_move(filePath, newPath)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment