Introduction

This tutorial shows you how you can rename files using R. The entire R-markdown document can be downloaded here.

How do I rename a batch of files?

This tutorial will show you hoq you can use R to rename many fiiles in an easy way.

The aim of the task here is to take all files ending in .Rmd, then adding *_cb* to their name, and then saving them in a folder called cbs which is a subfolder of the current working directory. So, if there is a file called test.Rmd, we want to change its name to test_cb.Rmd and then save that renamed file in the cbs folder.

Preparation and session set up

This tutorial is based on R. If you have not installed R or are new to it, you will find an introduction to and more information how to use R here. For this tutorials, we need to install certain packages from an R library so that the scripts shown below are executed without errors. Before turning to the code below, please install the packages by running the code below this paragraph. If you have already installed the packages mentioned below, then you can skip ahead and ignore this section. To install the necessary packages, simply run the following code - it may take some time (between 1 and 5 minutes to install all of the libraries so you do not need to worry if it takes some time).

# install packages
install.packages("knitr")
install.packages("tidyverse")
install.packages("here")
install.packages("flextable")
# install klippy for copy-to-clipboard button in code chunks
remotes::install_github("rlesur/klippy")

Now that we have installed the packages, we activate them as shown below.

# set options
options(stringsAsFactors = F)          # no automatic data transformation
options("scipen" = 100, "digits" = 12) # suppress math annotation
# activate packages
library(knitr)
library(tidyverse)
library(here)
library(flextable)
# activate klippy for copy-to-clipboard button
klippy::klippy()

Once you have installed R and RStudio and initiated the session by executing the code shown above, you are good to go.

Getting started

We begin by creating a list of the files you want to rename.


NOTE
You need to change the path that is used in the code below and include the path to the files on your computer! The code below will create a list of the files in the current working directory that end in “.Rmd”.


# list files
fnames  <- list.files(here::here(""), pattern = ".Rmd", full.names = T)

Let’s briefly inspect file names.

The inspection shows that the file names represent the location of the files on my computer. In a next step, we load the file content in a vector called fcontent.

fcontent <- sapply(fnames, function(x){
  x <- readLines(x)
  x <- paste0(x, sep = "\n", collapse = "")
})

Next, we edit the file names by only retaining the file name itself, removing the .Rmd- ending and then adding the desired *_cb.Rmd* ending.

fnames <- fnames %>%
  stringr::str_remove_all(".Rmd") %>%
  stringr::str_remove_all(".*/") %>%
  paste0(., "_cb.Rmd")

Let’s inspect file names again to see if changing the file names was successful.

We now save the files with a new name into the folder where we want them to be. To this end, we need to specify the con (the connection, i.e., the place where we want to store the file). In the present case, we extract the path to the working directory, then add cbs/ and then add the edited file name.

for (i in 1:length(fcontent)) {
  writeLines(text = fcontent[i],
    con = paste0(here::here("cbs"), "/", fnames[i], sep = ""))
}

One the code above is executed, the files were all in the cbs subfolder as desired.

Citation & Session Info

Schweinberger, Martin. 2021. Renaming files with R. Brisbane: The University of Queensland. url: https://slcladal.github.io/introviz.html (Version 2021.09.30).

@manual{schweinberger2021rename,
  author = {Schweinberger, Martin},
  title = {Renaming files with R},
  note = {https://slcladal.github.io/rename.html},
  year = {2021},
  organization = "The University of Queensland, School of Languages and Cultures},
  address = {Brisbane},
  edition = {2021.09.30}
}
sessionInfo()
## R version 4.1.1 (2021-08-10)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 19043)
## 
## Matrix products: default
## 
## locale:
## [1] LC_COLLATE=German_Germany.1252  LC_CTYPE=German_Germany.1252   
## [3] LC_MONETARY=German_Germany.1252 LC_NUMERIC=C                   
## [5] LC_TIME=German_Germany.1252    
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] flextable_0.6.8 here_1.0.1      forcats_0.5.1   stringr_1.4.0  
##  [5] dplyr_1.0.7     purrr_0.3.4     readr_2.0.1     tidyr_1.1.3    
##  [9] tibble_3.1.4    ggplot2_3.3.5   tidyverse_1.3.1 knitr_1.34     
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_1.0.7        lubridate_1.7.10  assertthat_0.2.1  rprojroot_2.0.2  
##  [5] digest_0.6.27     utf8_1.2.2        R6_2.5.1          cellranger_1.1.0 
##  [9] backports_1.2.1   reprex_2.0.1.9000 evaluate_0.14     httr_1.4.2       
## [13] highr_0.9         pillar_1.6.2      gdtools_0.2.3     rlang_0.4.11     
## [17] uuid_0.1-4        readxl_1.3.1      rstudioapi_0.13   data.table_1.14.0
## [21] klippy_0.0.0.9500 rmarkdown_2.5     munsell_0.5.0     broom_0.7.9      
## [25] compiler_4.1.1    modelr_0.1.8      xfun_0.26         systemfonts_1.0.2
## [29] pkgconfig_2.0.3   base64enc_0.1-3   htmltools_0.5.2   tidyselect_1.1.1 
## [33] fansi_0.5.0       crayon_1.4.1      tzdb_0.1.2        dbplyr_2.1.1     
## [37] withr_2.4.2       grid_4.1.1        jsonlite_1.7.2    gtable_0.3.0     
## [41] lifecycle_1.0.0   DBI_1.1.1         magrittr_2.0.1    scales_1.1.1     
## [45] zip_2.2.0         cli_3.0.1         stringi_1.7.4     fs_1.5.0         
## [49] xml2_1.3.2        ellipsis_0.3.2    generics_0.1.0    vctrs_0.3.8      
## [53] tools_4.1.1       glue_1.4.2        officer_0.4.0     hms_1.1.0        
## [57] fastmap_1.1.0     yaml_2.2.1        colorspace_2.0-2  rvest_1.0.1      
## [61] haven_2.4.3

Back to top

Back to HOME