This question already has an answer here:

Hopefully somebody can help me out with this,

I'm looking for a small script which does a keyword search in a PDF file (actually a folder of PDF files), and it needs to return all pages including the name of the file, where the keyword is found.

I have found the following script (over here https://ubuntuforums.org/showthread.php?t=1368062):


[ "$*" ] || { echo "You forgot a search string!" ; exit 1 ; }


for file in ./src/*.pdf ; do
   [ "$file" = '*.pdf' ] && echo "No PDF files found!" && exit 1
   pages=$(pdfinfo "$file" | awk '/Pages:/ { print $NF }')
   for ((i=1 ; i<=$pages ; i++)) ; do
      match=$(pdftotext -q -f $i -l $i "$file" - | grep -m 1 "$*")
      [ "$match" ] && echo "Page $i in $file" && found=0

[ "$found" -ne 0 ] && echo "No search string matches found"

It does return most of the hits, but still, the search functionality inside Adobe Acrobat Reader and Mac Preview does return way more matches. Anyone who recognises what might be the problem?

My guess is it fails on a character before and/or after the search keyword, but that's just a guess .

If it includes the number of matches per page, it's truly perfect!

marked as duplicate by user88036, countermode, RalfFriedl, Caleb, meuh Sep 26 '18 at 17:50

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


I would use pdfgrep:

pdfgrep -p "your search string" src/*.pdf

will output the matching page numbers, with a count per page.

This might not deal with the missing matches; the reasons for those depend on the way the PDFs are constructed (in particular, how the text is assembled).

  • Thanks so much! Pdfgrep is far more accurate! It seems to work perfectly – Erik van de Ven Sep 25 '18 at 9:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.