【问题标题】:Is there a way to add a prefix/suffix to all similar files in subfolders of a directory?有没有办法为目录子文件夹中的所有类似文件添加前缀/后缀?
【发布时间】:2022-01-21 13:46:36
【问题描述】:

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

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

【问题讨论】:

  • “Berries”文件夹发生了什么?

标签: r path file-rename prefix


【解决方案1】:

试试这个:

# 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)

【讨论】:

  • 谢谢!是的,对浆果文件夹感到抱歉!这就是我需要的!如果您可以的话,还有一个快速的问题:文件路径/子文件夹的前缀可以按不同的顺序排列吗?还是需要一个完全不同的过程?
  • @JimboBiggly 使用预期输出编辑您的问题。无论如何,这个答案应该足以根据您的需要操作文件名。
猜你喜欢
  • 2013-02-04
  • 1970-01-01
  • 2015-07-02
  • 2010-09-29
  • 2017-01-02
  • 2018-07-25
  • 2023-03-05
  • 2020-11-10
  • 2015-01-18
相关资源
最近更新 更多