3  Rename files procedurally

You’ll sometimes have folders with filenames that make no sense to you or need organising.

This script simply reads a list of files, does stuff to the names and then saves the changes.

3.1 Libraries

library(tidyverse)

3.2 Procedure

3.2.1 Get a list of the original file names

xx<-list.files("data/filenames/",full.names = T,recursive = T)
xx
[1] "data/filenames//01_A.csv" "data/filenames//02_B.csv"
[3] "data/filenames//03_C.csv" "data/filenames//04_D.csv"

3.2.2

Manipulate the strings

xxx<-case_when(
               str_detect (xx,"_A") ~ str_replace(xx, "_A", "_D"),
               str_detect (xx,"_B") ~ str_replace(xx, "_B", "_A"),
               str_detect (xx,"_C") ~ str_replace(xx, "_C", "_B"),
               str_detect (xx,"_D") ~ str_replace(xx, "_D", "_C")
                )
xxx
[1] "data/filenames//01_D.csv" "data/filenames//02_A.csv"
[3] "data/filenames//03_B.csv" "data/filenames//04_C.csv"

3.2.3

Loop across all names, replacing the filename where needed

for(i in 1:length(xx)){
  print(i)
  print(str_c(xx[i]," ",xxx[i]))

  if(xx[i]!=xxx[i]){
  system(
        str_c("mv ",xx[i]," ",xxx[i])
      )
  }
  }
[1] 1
[1] "data/filenames//01_A.csv data/filenames//01_D.csv"
[1] 2
[1] "data/filenames//02_B.csv data/filenames//02_A.csv"
[1] 3
[1] "data/filenames//03_C.csv data/filenames//03_B.csv"
[1] 4
[1] "data/filenames//04_D.csv data/filenames//04_C.csv"

3.2.4