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]。