2

I find the page numbers of a multiline pattern in a pdf file, by How shall I grep a multi-line pattern in a pdf file and in a text file? and How can I search a string in a pdf file, and find the physical page number of each page where the string appears?

$ pdfgrep -Pn '(?s)image\s+?not\s+?available'  main_text.pdf 
49: image
   not
available
51: image
   not
available
53: image
   not
available
54: image
   not
available
55: image
   not
available

I would like to extract the page number only, but because the pattern is multiline, I get

$ pdfgrep -Pn '(?s)image\s+?not\s+?available'  main_text.pdf | awk -F":" '{print $1}'
49
   not
available
51
   not
available
53
   not
available
54
   not
available
55
   not
available

instead of

49
51
53
54
55

I wonder how I can extract the page numbers only, regardless if the pattern is multiline? Thanks.

5

It's a bit hacky, but since you are already using a perl compatible RE, you could use \K "keep left" modifier to match everything in your expression (and anything else up to the next line end) but exclude it from the output:

pdfgrep -Pn '(?s)image\s+?not\s+?available.*?$\K'  main_text.pdf

The output will still include the : separator however.

  • Thanks. It works. Could you try to explain again what '(?s)image\s+?not\s+?available.*?$\K' means? Could '(?s)image\s+?not\s+?available.*?$\K' be written in terms of Python style RE which I am more familiar with? – Tim Jul 22 '18 at 23:48
  • @Tim sorry I am not fluent enough in Python to attempt that – steeldriver Jul 22 '18 at 23:53
  • Is there some website which can translate between regex of different flavors, for example from Perl regex to Python regex? Thanks. – Tim Jul 27 '18 at 1:16
1

Add $0~":" as awk recognizer. I.e., you get the line:

 .... | awk -F":" '$0~":"{print $1}'

By that, the printout will only be when the input line has a ":" in it, and other lines are just discarded.

  • Thanks. What if the pattern matches a string containing : in the second line? – Tim Jul 22 '18 at 23:41
  • Yes, that will print as well. You can do man awk for ways of sharpening the recognition, e.g., only accept lines starting with numbers and colon, or something. If that's still ambiguous, you're out of luck with this approach, and may need a more refined pdf parser. – Ralph Rönnquist Jul 22 '18 at 23:45

Your Answer

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

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