如何移除Latex文稿中未使用的图片?
识别LaTeX手稿中未使用图片的便捷方法
终端命令批量检索(适用于Linux/macOS,Windows可用Git Bash/PowerShell)
- 先在LaTeX主文件所在目录打开终端,执行命令提取所有被引用的图片文件名并保存:
grep -oP '(?<=includegraphics\[?.*?\]{)[^}]+' *.tex > used_images.txt
这个命令会扫描所有.tex文件,把includegraphics命令里的图片名提取出来,存到used_images.txt中。 - 对比图片文件夹里的文件,找出未被引用的:
假设图片存在images文件夹,执行:comm -23 <(ls images/ | sort) <(sort used_images.txt)
输出结果就是图片文件夹里没被用到的文件。
利用LaTeX辅助文件(.aux)
- 正常编译一次LaTeX文档,生成
.aux辅助文件,里面记录了实际调用的资源。 - 用gawk提取图片名:
gawk '/\\@writefile.*\\includegraphics/{match($0, /\{[^\}]+\}/, a); print substr(a[0],2,length(a[0])-2)}' main.aux > used_images.txt
把main.aux换成你的主文档对应的aux文件名,之后同样可以用终端命令对比图片文件夹的文件。
自定义Python脚本
如果终端命令用着不习惯,可写个简单脚本自动对比:
import os import re # 替换成你的实际路径 tex_directory = "./" image_directory = "./images" # 收集所有被引用的图片名 used_images = set() tex_files = [file for file in os.listdir(tex_directory) if file.endswith(".tex")] # 匹配includegraphics命令里的图片名 img_pattern = re.compile(r'includegraphics\[?.*?\]{([^}]+)}') for tex_file in tex_files: with open(os.path.join(tex_directory, tex_file), 'r', encoding='utf-8') as f: content = f.read() found_imgs = img_pattern.findall(content) used_images.update(found_imgs) # 找出图片文件夹里未被引用的文件 unused_images = [] for img_file in os.listdir(image_directory): # 兼容引用时带后缀/不带后缀的情况 img_base_name = os.path.splitext(img_file)[0] if img_file not in used_images and img_base_name not in used_images: unused_images.append(img_file) print("未使用的图片列表:") for img in unused_images: print(img)
- 运行前确保装了Python,把路径改成自己的,执行脚本就能直接得到未使用的图片清单。
内容的提问来源于stack exchange,提问作者Alex K
相关产品推荐
相关产品推荐

