Linux大目录下PDF文件分块渐进列出及断点续询方案求助
问题描述
处理超大目录下的PDF文件列表时遇到以下问题:
- 执行
ls -l *.pdf耗时极长,断开连接后必须从头重新执行 - 尝试过
ls -l /**/*.pdf、find ./*.pdf -type d -maxdepth 1 -printf '%f\n' >> files.txt以及Python的glob.glob(f"{dir}/**/*.pdf", recursive=True)等方式,均耗时数小时且无进度反馈 - 需求:实现分块渐进式列出文件,单个目录内可从已完成位置续接,断开连接后无需从头开始
可行方案与思路
1. 基于find的断点续传脚本
利用目录排序和进度记录实现续接:
- 先导出所有目录并排序:
find . -type d | sort > dirs.txt - 编写循环脚本逐目录处理,同时记录已完成目录:
while IFS= read -r dir; do # 跳过已处理的目录 grep -q "^$dir$" processed_dirs.txt && continue # 列出当前目录下的PDF并追加到结果文件(忽略无PDF的报错) ls -l "$dir"/*.pdf >> pdf_list.txt 2>/dev/null # 标记当前目录已处理 echo "$dir" >> processed_dirs.txt done < dirs.txt
断开后重新执行脚本,会自动跳过已处理的目录,从上次中断的位置继续。
2. 拆分目录列表分块处理
如果目录数量极大,可先拆分目录列表,分块处理便于管理:
- 拆分目录列表为每个包含1000个目录的分块文件:
split -l 1000 dirs.txt dir_chunk_ - 逐块处理并记录已完成的分块:
for chunk in dir_chunk_*; do # 跳过已处理的分块 [ -f processed_chunks.txt ] && grep -q "^$chunk$" processed_chunks.txt && continue # 处理当前分块内的所有目录 while IFS= read -r dir; do ls -l "$dir"/*.pdf >> pdf_list.txt 2>/dev/null done < "$chunk" # 标记分块已处理 echo "$chunk" >> processed_chunks.txt done
3. Python实现断点续接的递归遍历
用Python手动控制遍历流程,精准记录进度:
import os def scan_pdfs(root_dir, progress_file="scan_progress.txt", output_file="pdf_list.txt"): # 读取已处理的目录路径 processed_dirs = set() if os.path.exists(progress_file): with open(progress_file, "r") as f: processed_dirs = set(f.read().splitlines()) # 追加模式写入结果和进度 with open(output_file, "a") as out_f, open(progress_file, "a") as prog_f: for root, _, files in os.walk(root_dir): if root in processed_dirs: continue # 写入当前目录下的所有PDF路径 for file in files: if file.lower().endswith(".pdf"): out_f.write(f"{os.path.abspath(os.path.join(root, file))}\n") # 立即写入进度,避免意外中断丢失 prog_f.write(f"{root}\n") prog_f.flush() if __name__ == "__main__": scan_pdfs("/path/to/your/target/dir")
这个脚本会逐目录处理,每完成一个目录就写入进度文件,断开后重新运行会自动跳过已处理的目录。
4. displit结合进度记录的方案
displit可将大目录树拆分为多个独立子树,结合断点续传逻辑实现并行/续处理:
- 拆分目录树为4个独立子树(可调整数量):
displit -n 4 /path/to/your/dir split_subdirs_ - 对每个拆分后的子目录,使用上述任意一种断点续传脚本单独处理,记录每个子目录的处理进度。断开后只需针对未完成的子目录重新执行即可。
内容的提问来源于stack exchange,提问作者Naga kiran
相关产品推荐
相关产品推荐

