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

如何在R语言中按ID筛选并移动指定格式的PDF文件?

用tidyverse筛选并移动指定ID的PDF文件

步骤1:加载所需包

先加载tidyverse生态中处理文件和字符串的工具包:

library(tidyverse)
library(fs)

步骤2:读取目录中的PDF文件

用fs::dir_ls读取目标目录下的所有PDF文件,转成tibble格式方便后续数据处理:

# 替换为你的源目录实际路径
source_dir <- "path/to/your/source/folder"
files_tbl <- dir_ls(source_dir, regexp = "\\.pdf$") %>%
  as_tibble_col(column_name = "full_path") %>%
  mutate(file_name = path_file(full_path)) # 提取不带路径的纯文件名

步骤3:从文件名中提取ID

利用stringr::str_extract结合正则表达式,精准匹配文件名最后一个-后、.pdf前的4-6位数字(兼容当前及未来的ID长度):

files_tbl <- files_tbl %>%
  mutate(id = str_extract(file_name, "-([0-9]{4,6})\\.pdf$", group = 1))

正则说明:-[0-9]{4,6}\\.pdf$ 匹配文件名末尾的-+4-6位数字+.pdf,group=1专门提取括号内的数字部分作为ID。

步骤4:筛选目标ID对应的文件

定义你的目标ID向量,用dplyr::filter筛选出符合条件的文件:

# 替换为你需要筛选的ID向量
target_ids <- c("5555", "12345", "678901")
filtered_files <- files_tbl %>%
  filter(id %in% target_ids)

步骤5:移动筛选后的文件

用fs::file_move完成文件移动,比system()更适配tidyverse风格且跨平台通用:

# 替换为你的目标目录实际路径
target_dir <- "path/to/your/target/folder"
# 确保目标目录存在,不存在则自动创建
dir_create(target_dir)

# 执行移动操作
filtered_files %>%
  pull(full_path) %>%
  file_move(new_path = path(target_dir, path_file(.)))

完整整合代码

library(tidyverse)
library(fs)

# 配置核心参数
source_dir <- "path/to/source/folder"
target_dir <- "path/to/target/folder"
target_ids <- c("5555", "12345", "678901")

# 一键执行全流程
dir_create(target_dir)

dir_ls(source_dir, regexp = "\\.pdf$") %>%
  as_tibble_col("full_path") %>%
  mutate(
    file_name = path_file(full_path),
    id = str_extract(file_name, "-([0-9]{4,6})\\.pdf$", group = 1)
  ) %>%
  filter(id %in% target_ids) %>%
  pull(full_path) %>%
  file_move(new_path = path(target_dir, path_file(.)))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 11:50:21