繁体   English   中英

有没有办法为目录子文件夹中的所有类似文件添加前缀/后缀?

[英]Is there a way to add a prefix/suffix to all similar files in subfolders of a directory?

我有一个包含几个子文件夹的目录,我将举一个例子:

Fruit-> Red->Berries->strawberry.jpg  
Fruit-> Red->Berries->raspberry.jpg

我想将子文件夹名称包含在我的文件名中,例如:

From: strawberry.jpg  
To: Fruit_Red_strawberry.jpg

但我也希望能够为所有以 .JPG 结尾的文件添加前缀。 例如:

Fruit_Red_strawberry.jpg  
Fruit_Red_raspberry.jpg

添加YES_前缀,使其成为:

YES_Fruit_Red_strawberry.jpg  
YES_Fruit_Red_raspberry.jpg

尝试这个:

# use list.files with full paths
#x <- list.files(full.names = TRUE)

#example files with full paths for testing
x <- c("Fruit/Red/Berries/strawberry.jpg",
       "Fruit/Red/Berries/raspberry.jpg", 
       "Fruit/Red/Berries/test.txt")

#replace / with _
newNames <- gsub("/", "_", x, fixed = TRUE)

#prefix YES
newNames <- ifelse(tools::file_ext(x) == "jpg",
                   paste0("YES_", newNames), newNames)

#prefix with folder
newNames <- paste(tools::file_path_sans_ext(x), newNames, sep = "/")

newNames
# [1] "Fruit/Red/Berries/strawberry/YES_Fruit_Red_Berries_strawberry.jpg"
# [2] "Fruit/Red/Berries/raspberry/YES_Fruit_Red_Berries_raspberry.jpg"  
# [3] "Fruit/Red/Berries/test/Fruit_Red_Berries_test.txt" 

#then rename old with new names
#file.rename(x, newNames)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM