天天看點

R語言——批量重命名檔案前言源代碼小結

R語言——批量重命名檔案

  • 前言
  • 源代碼
  • 小結

前言

針對指定檔案夾裡的檔案,并依據參考表批量重命名檔案。

提示:以下是本篇文章正文内容,下面案例僅供學習參考

源代碼

# 批量重命名檔案
# 批量重命名不可以撤銷,請慎重
# 參考excel表中必須含有舊名、新名兩個字段名以及相應的内容
# WorkingDirectory --------------------------------------------------------
pkg <- c('dplyr', 'openxlsx', 'stringr', 'pbapply')
sapply(pkg, library, character.only = T) #加載相應的包
options(stringsAsFactors = F)
choose.dir() %>% setwd() #選擇含有待重命名的目标檔案夾
da1 <- read.xlsx(choose.files()) #選擇用于重命名檔案的參考excel表
# rename ------------------------------------------------------------------
target_1 <- getwd()
t_file_1 <- data.frame(old = list.files(target_1), new = NA) 
t_file_1$v1 <- t_file_1$old %>% str_remove('\\.[^\\.]\\w+$')
t_file_1$v2 <- t_file_1$old %>% str_extract('\\.[^\\.]\\w+$')

# 檢查
a <- t_file_1$v1 %>% setdiff(da1$舊名)
if(length(unique(t_file_1$v1)) != length(unique(da1$舊名))) 
  warning('Error: 所選檔案夾裡檔案名稱與excel表中去重的舊名稱長度不一緻')
if(length(a) != 0) warning('Error: 所選檔案夾裡含有excel表中未聲明的舊名稱,如——' %>% 
                             paste0(a %>% paste(sep = ',')))

t_file_1$new <- t_file_1$v1 %>% match(da1$舊名) %>% da1$新名[.]
t_file_1$new <- t_file_1$new %>% paste0(t_file_1$v2)
t_file_1 %>% select(舊名, 新名) %>% pbapply(1, function(df) 
  file.rename(paste0( target_1,'/', df[1] ) , paste0( target_1,'/' ,df[2] )))
           

小結

R語言——批量重命名檔案案例如上所述。有問題的小夥伴可Email我,郵箱位址:[email protected]。

繼續閱讀