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



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

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)

最新更新