[英]Renaming files in directory based on filename using R
我有一個數據框(FilesDf),其中包含每個文件名以及需要對其進行替換的文件(FilesDf $ FileTags)。
FileName Filename FileTags
H:/name/+Sm,Jon.docx +Sm,Jon.docx RR UB AF-
H:/name/+Suth,Jane.docx +Suth,Jane.docx AF-
H:/name/+Dunn,Robert.docx +Dunn,Robert.docx RR LL-
對於此文件夾中的每個文件名,我需要將FileTag附加為前綴。 文件名需要如下所示:
RR UB AF-Sm,Jon.docx
AF-Suth,Jane.docx
RR LL-Dunn,Robert.docx
我的嘗試:
Filepath <- "H:/name/"
files <- list.files(Filepath,pattern = "*.doc",full.names = T)
nrow<-nrow(FilesDf)
for(i in nrow){
sapply(files,FUN=function(eachPath){
file.rename(from=eachPath,to= sub(pattern="\\+",
FilesDf$FileTags[i],eachPath))
})
}
但這導致所有文件具有相同的前綴,而不是具有與文件名正確對應的前綴。
我建議您分階段進行操作,部分是為了確保它能正常工作(測試),部分是因為它易於維護/擴展。
FilesDf$FileName2 <- file.path(dirname(FilesDf$FileName),
gsub("\\+", "", paste0(FilesDf$FileTags, FilesDf$Filename)))
FilesDf
# FileName Filename FileTags FileName2
# 1 H:/name/+Sm,Jon.docx +Sm,Jon.docx RR UB AF- H:/name/RR UB AF-Sm,Jon.docx
# 2 H:/name/+Suth,Jane.docx +Suth,Jane.docx AF- H:/name/AF-Suth,Jane.docx
# 3 H:/name/+Dunn,Robert.docx +Dunn,Robert.docx RR LL- H:/name/RR LL-Dunn,Robert.docx
如果新名稱( $FileName2
)看起來不錯,則
ign <- mapply(file.rename, FilesDf$FileName, FilesDf$FileName2)
應該管用。
(最初,我對$FileName
與$Filename
分散了注意力,卻錯過了第二個...)
數據:
FilesDf <- structure(list(FileName = c("H:/name/+Sm,Jon.docx", "H:/name/+Suth,Jane.docx",
"H:/name/+Dunn,Robert.docx"), Filename = c("+Sm,Jon.docx", "+Suth,Jane.docx",
"+Dunn,Robert.docx"), FileTags = c("RR UB AF-", "AF-", "RR LL-"
)), row.names = c(NA, -3L), class = c("data.frame"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.