You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中用file.copy()匹配含两位任意数字的文件并迁移

在R中复制带可变两位数字后缀的目标文件

解决方案步骤:

  • 定位源文件夹下符合Some_file_+两位数字+.xlsx命名规则的文件
  • 提取该文件名,构造源路径与目标路径后执行复制操作

完整代码:

# 定义源文件夹和目标文件夹路径
source_dir <- "C:/Folder1/Folder2"
target_dir <- "C:/Folder1/AnotherFolder"

# 精准匹配符合规则的文件:以Some_file_开头,后跟两位数字,以.xlsx结尾
target_file <- list.files(path = source_dir, 
                          pattern = "^Some_file_\\d{2}\\.xlsx$", 
                          full.names = FALSE)

# 构造完整的源文件路径和目标文件路径(file.path自动适配路径分隔符,比paste0更安全)
source_path <- file.path(source_dir, target_file)
target_path <- file.path(target_dir, target_file)

# 执行文件复制,overwrite参数可覆盖目标路径已存在的同名文件(按需调整)
file.copy(from = source_path, to = target_path, overwrite = TRUE)

代码说明:

  • list.files()的pattern参数使用正则表达式^Some_file_\\d{2}\\.xlsx$:
    • ^和$限定字符串首尾,确保完全匹配目标命名规则
    • \\d{2}匹配恰好两位数字
    • \\.转义点号(正则中点号为通配符,需转义才能匹配文件名里的点)

如果要贴合你提供的paste0()框架,可提取文件名中的两位数字后拼接路径:

# 提取文件名中的两位数字
file_num <- sub("^Some_file_(\\d{2})\\.xlsx$", "\\1", target_file)

# 用paste0构造路径并复制
file.copy(from = paste0("C:/Folder1/Folder2/Some_file_", file_num, ".xlsx"),
          to = paste0("C:/Folder1/AnotherFolder/Some_file_", file_num, ".xlsx"),
          overwrite = TRUE)

内容的提问来源于stack exchange,提问作者geoscience123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 17:07:18