用R重命名子目录中的文件

时间:2018-01-28 23:13:26

标签: r file path file-rename

我想重命名子目录中的所有jpeg文件以及子目录名称和jpeg文件,例如

WorkingDirectory/FolderA/ -> a.jpg
WorkingDirectory/FolderB/ -> a.jpg

想要改变为

WorkingDirectory/FolderA/ -> FolderA-a.jpg
WorkingDirectory/FolderB/ -> FolderB-a.jpg

到目前为止,我正在使用

old.names <- list.files(path = ".", pattern = "jpeg$", recursive = TRUE)

new.names <- old.names
new.names  = gsub("/", "-", new.names)
new.names  = gsub(".jpeg", "", new.names)

final <- data.frame(do.call(cbind,mget(c('old.names','new.names'))))

final$old.names  = gsub("", "", final$old.names)
final$new.names  = gsub("", "", final$new.names)
file.rename(final$old.names, paste0(final$new.names, ".jpeg"))

我能够重命名文件,但我面对上述代码的问题是,它将所有文件移动到工作目录中,因为它们应保留在子目录中。

2 个答案:

答案 0 :(得分:2)

上面的例子似乎已经足够了:

old.names <- list.files(path = ".", pattern = "jpeg$", recursive = TRUE)

new.names <- old.names
new.names <- gsub("/", "-", new.names)
new.names <- file.path(dirname(old.names), new.names)

file.rename(old.names, new.names)

答案 1 :(得分:1)

您正在从示例代码中的new.names剥离文件夹名称。

这应该有效:

old.names <- list.files(path = ".", pattern = "jp[e]*g$", recursive = TRUE)
old.names;
#[1] "tmp/FolderA/a.jpg" "tmp/FolderB/b.jpg"

new.names <- sapply(strsplit(old.names, "/"), function(x)
    sprintf("%s/%s",
        paste0(x[1:(length(x) - 1)], collapse = "/"),
        paste0(x[(length(x) - 1):length(x)], collapse = "-")));
new.names;
#[1] "tmp/FolderA/FolderA-a.jpg" "tmp/FolderB/FolderB-b.jpg"

file.rename(old.names, new.names);

说明:在old.names上拆分"/",然后通过将第一个new.names条目与n-1(即文件夹)连接起来构建"/",然后添加通过将最后一个文件夹名称和旧文件名与"-"连接而生成的新文件名。