2

I want to search for a specific keyword in multiple pdf file using pdftotext command. Normally we can search inside a single pdf file using the following command:

pdftotext file.pdf - | grep keyword

But what we wil have to do if we want to search in multiple pdf files?

2

You could use a shell loop:

for file in *pdf; do pdftotext "$file" - | grep keyword; done

Or, to print the name of the PDF the pattern was found in:

for file in *pdf; do 
    echo "-----------$file----------"
    pdftotext "$file" - | grep keyword
done
  • What about: pdftotext "$file" - | grep keyword && echo "$file" as an alternative to always echoing the filename? – Jeff Schaller Sep 10 '15 at 14:54
  • @JeffSchaller that would simply echo the file name at the end of all the results found in that file. For multiple lines of results across many files, that will be hard to read. – terdon Sep 10 '15 at 15:07
  • True; the question doesn't specify an output format, so I'll just leave my last idea here (changing it to grep -q): for file in *pdf; do pdftotext "$file" - | grep -q keyword && echo Found in $file done – Jeff Schaller Sep 10 '15 at 18:08
2

There's a tool for that: pdfgrep. It's available in all good¹ distributions.

pdfgrep keyword *.pdf

¹ Here I define “good” as “including pdfgrep”. This includes Debian and Fedora.

1

Here's one way to do it:

(pdftotext file1.pdf -; pdftotext file2.pdf -;) | grep keyword

...where you could continue with additional files inside the parenthesis. You would lose track of which file had the grep "hit", but you could repeat the grep with partitions of the files until you found the matching file(s).

  • is there any way of using wildcards here? @Jeff Schaller – user133557 Sep 10 '15 at 14:37
  • pdftotext appears to only take one input file at a time. If you want to use wildcards, it would have to be in a loop around calling pdftotext individually. -- like @terdon just posted :) – Jeff Schaller Sep 10 '15 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy