如何在目录/子目录中搜索PDF文件的内容?我在找一些命令行工具。grep似乎不能搜索PDF文件。


当前回答

我喜欢@sjr的答案,但我更喜欢xargs vs -exec。我发现xargs更通用。例如,使用-P,我们可以在必要时利用多个cpu。

find . -name '*.pdf' | xargs -P 5 -I % pdftotext % - | grep --with-filename --label="{}" --color "pattern"

其他回答

还有pdfgrep,它做的正是它的名字所暗示的。

pdfgrep -R 'a pattern to search recursively from path' /some/path

我用它做过简单的搜索,效果很好。

(Debian、Ubuntu和Fedora中都有软件包。)

从1.3.0版本开始,pdfgrep支持递归搜索。这个版本从Ubuntu 12.10 (Quantal)开始在Ubuntu中可用。

使用pdfgrep:

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.

如果你想用pdftotext查看文件名,使用以下命令:

find . -name '*.pdf' -exec echo {} \; -exec pdftotext {} - \; | grep "pattern\|pdf" 

你需要一些工具,如pdf2text,首先将pdf转换为文本文件,然后在文本中搜索。(您可能会错过一些信息或符号)。

如果你正在使用一种编程语言,很可能有专门为此目的编写的pdf库。例如:http://search.cpan.org/dist/CAM-PDF/ for Perl

我写了这个破坏性的小脚本。祝你玩得开心。

function pdfsearch()
{
    find . -iname '*.pdf' | while read filename
    do
        #echo -e "\033[34;1m// === PDF Document:\033[33;1m $filename\033[0m"
        pdftotext -q -enc ASCII7 "$filename" "$filename."; grep -s -H --color=always -i $1 "$filename."
        # remove it!  rm -f "$filename."
    done
}