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

如何通过Bash脚本利用PDF提取的字符串批量重命名文件

批量重命名PDF:从引用信息提取标题作为新文件名

问题背景

已通过pdfgrep "To cite this article" *.pdf从文件夹内多个PDF中提取出引用信息,输出示例如下:

09592296.2016.1169809.pdf: To cite this article: T.G. Otte (2016) Black, J. (2016). Geopolitics and the Quest for Dominance,

14650040008407697.pdf:To cite this article: Stanley D. Brunn (2000): Towards an understanding of the

14650040600767859.pdf:To cite this article: Virginie Mamadouh & Gertjan Dijkink (2006) Geopolitics, International Relations

14650040802203927.pdf:To cite this article: Tristan Sturm (2008) Critical Methodological Geopolitics: Discourse Analysis/

14650040903141398.pdf:To cite this article: Sean Carter (2009) Geopolitics and the Screen: War, the Body and Violence,

14650045.2010.493996.pdf:To cite this article: John Agnew (2011): Capitalism, Territory and “Marxist Geopolitics”, Geopolitics,

14650045.2010.493997.pdf:To cite this article: Jeremy Black (2011): Towards A Marxist Geopolitics, Geopolitics, 16:1, 234-235

需要将原PDF文件重命名为对应的文章标题(如14650040903141398.pdf→Geopolitics and the Screen: War, the Body and Violence.pdf)。

解决方案:Bash脚本批量处理

以下脚本可直接处理pdfgrep的输出,自动提取标题并安全重命名文件:

#!/bin/bash

# 直接读取pdfgrep的输出,逐行处理
pdfgrep "To cite this article" *.pdf | while IFS= read -r line; do
    # 提取原PDF文件名
    old_file=$(echo "$line" | cut -d':' -f1)
    # 从引用内容中提取标题:匹配年份括号后的内容
    title=$(echo "$line" | sed -E 's/.*\([0-9]{4}\)(\.|:)?\s*(.*)/\2/' | xargs)
    # 处理文件名非法字符:替换/、:等为下划线,移除末尾逗号
    safe_title=$(echo "$title" | sed -E 's/[\/:*?"<>|]/_/g' | sed 's/,$//')
    # 重命名文件(先echo测试,确认无误后去掉echo)
    echo mv -v "$old_file" "${safe_title}.pdf"
done

步骤说明

  1. 提取原文件名:通过cut命令分割冒号前的部分,得到原PDF文件名。
  2. 提取标题:用正则匹配年份(如(2016))后的内容,xargs去除标题前后多余空格。
  3. 安全处理标题:替换文件名不允许的字符(/、:、?等)为下划线,移除标题末尾的逗号。
  4. 测试与执行:脚本中先用echo打印重命名命令,确认所有操作符合预期后,删除echo即可执行真实重命名。

注意事项

  • 重复标题处理:若多个文件提取的标题相同,重命名会覆盖文件。可在脚本中添加判断逻辑,给重复标题加序号(如标题_1.pdf)。
  • 异常行处理:部分行可能无法正确提取标题,需手动检查并修改正则或单独处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 01:09:29