我该如何在目录/子目录中搜索PDF文件的内容?我正在寻找一些命令行工具。似乎grep
无法搜索PDF文件。
我该如何在目录/子目录中搜索PDF文件的内容?我正在寻找一些命令行工具。似乎grep
无法搜索PDF文件。
有一个开源共享资源的grep工具crgrep,它可以在PDF文件以及其他资源中搜索,例如嵌套在档案中的内容、数据库表、图像元数据、POM文件依赖和Web资源,以及这些的组合,包括递归搜索。
文件选项卡下的完整描述几乎涵盖了该工具支持的内容。
我作为一个开源工具开发了crgrep。
你需要一些工具,如pdf2text,先将你的pdf转换为文本文件,然后在文本中搜索。(你可能会错过一些信息或符号)。
如果你正在使用编程语言,那么可能有专门用于此目的的pdf库。例如,Perl的http://search.cpan.org/dist/CAM-PDF/。
感谢这里提出的所有好主意!
我尝试了xargs方法,但正如在这里指出的那样,xargs会使包括打印实际文件名变得不可能(或非常困难)...
所以我尝试了用GNU parallel完成整个事情。
parallel "pdftotext -q {} - | grep --with-filename --label='['{}']' --color=always --context=5 'pattern'" ::: *.pdf
--context=5
)。-q
,pdftotext将不会打印任何错误消息或警告(安静模式)。[]
作为标签,而不是花括号{}
。如果您想要花括号,则--label='{'{}'}'
可以实现。请注意,{}
将被GNU parallel替换为实际文件名,例如'Example portable document file name with spaces.pdf'
({}
已经使用单引号'
)。--label={}
,只会打印文件名,这可能是显示文件名的首选方式。--color=always
与grep强制执行。--ignore-case
。如果应递归处理所有PDF文件,包括当前目录(.
)中的所有子目录,则可以通过find来完成:
find . -type f -iname '*.pdf' -print0 | parallel -0 "pdftotext -q {} - | grep --with-filename --label='['{}']' --color=always --context=5 'pattern'"
-iname '*.pdf'
不区分大小写,而 -name '*.pdf'
只包括小写 .pdf 文件(通常情况)。由于有时我也会遇到扩展名为大写 .PDF 的 Windows PDF 文件,所以我更倾向于使用 -iname
。-print
find 选项(而非 -print0
),因此它将基于行(每行一个文件名),然后并行命令中必须省略 -0
(NUL 分隔符)。--ignore-case
将使搜索忽略大小写。在整个命令行中玩耍时的一般建议是,使用 parallel --dry-run
将打印将要执行的命令。
$ find . -type f -iname '*.pdf' -print0 | parallel --dry-run -0 "pdftotext -q {} - | grep --with-filename --label='['{}']' --color=always --ignore-case --context=5 'pattern'"
pdftotext -q ./test PDF file 1.pdf - | grep --with-filename --label='['./test PDF file 1.pdf']' --color=always --ignore-case --context=5 'pattern'
pdftotext -q ./subdir1/test PDF file 2.pdf - | grep --with-filename --label='['./subdir1/test PDF file 2.pdf']' --color=always --ignore-case --context=5 'pattern'
pdftotext -q ./subdir2/test PDF file 3.pdf - | grep --with-filename --label='['./subdir2/test PDF file 3.pdf']' --color=always --ignore-case --context=5 'pattern'
pdfgrep -HinR 'FWCOSP' DatenModel/
DatenModel/
中搜索单词FWCOSP
。我正在使用的选项是:
-i : Ignores, case for matching
-H : print the file name for each match
-n : prefix each match with the number of the page where it is found
-R : same as -r, but it also follows all symlinks.