1

Currently, I am working with a long list of files. They have a name pattern of SB_xxx_(parts). (different extensions), where xxx refers to an item code.

SB_19842.png
SB_19842_head.png
SB_19842_hand.png
SB_19842_head.pdf
...

It is found that many of these codes have incorrect entries. I got two columns in hand: One is for old codes and one is new codes (let's say A & B). I hope to change all those old codes in the file names to the new code.

  old    new
12154  24124
92482  02425
    .....

My first thought is to use file.rename() However, it is a one-to-one changing approach. I cannot do this because every item has a different number of parts and different file extensions.

Is there any recursive method that can simply change all incorrect file names with strings in A and replace them with strings in B? Anyone get an idea, please?

thelatemail
  • 91,185
  • 12
  • 128
  • 188
  • Something like this should cover it. https://stackoverflow.com/questions/64597819/match-and-replace-words-in-char-vector/64601011 – thelatemail Feb 23 '22 at 04:58

1 Answers1

0

A loop solution with purrr::map2 at the end:

library(purrr)
#create files to rename
file.create("SB_19842.png")
file.create("SB_19842_head.png")
file.create("SB_19842_hand.png")
file.create("SB_19842_head.pdf")
file.create("SB_12154.png")
file.create("SB_12154_head.png")
file.create("SB_12154_hand.png")
file.create("SB_12154_head.pdf")
# a dataframe with old a nd new patterns
file_names <- data.frame(
  old = c("19842", "12154"),
  new = c("new1", "new2")
)
# old filenames from the directory, specify path if needed
file_names_SB <- list.files(pattern = "SB_")
# function to substitute one type of code with another
sub_one_code <- function(old_code, new_code, file_names_original){
  gsub(paste0("SB_", old_code), paste0("SB_", new_code), file_names_original)
}
# loop to substitute all codes
new_file_names <- file_names_SB
for (row in 1:nrow(file_names)){
  new_file_names <- sub_one_code(file_names[row, "old"], file_names[row, "new"], new_file_names)
}
# rename all the files
map2(file_names_SB,
     new_file_names,
     file.rename)

@thelatemail provided a link with more elegant solutions for generating new file names.

altynbei
  • 87
  • 1
  • 8