我有各种各样可搜索的PDF文件,我经常使用pdfgrep
命令同时搜索所有文件中的特定模式。我的正则表达式知识有限,我不确定如何解决换行符和页面布局。
例如,我想在下面的每个示例中找到模式"ignor.{0,10}layout"
:
This is a rather difficult You see, I would like to ignore
task that I am trying to page layout and still find the
achieve. pattern I am looking for.
This is a rather difficult This is because I would like to ig-
task that I am trying to nore page layout and still find the
achieve. pattern I am looking for.
在两个示例中,我希望前两行由
报告pdfgrep -n "ignor.{0,10}layout" *
但是这样做失败是因为:
ignor
和layout
之间有超过10个字符。 ignor
被切成两半。是否存在可以完全解决此问题的正则表达式?
答案 0 :(得分:1)
pdfgrep
没有将换行解释为零字节所必需的-z
标志。您可以对pdftotext
使用变通办法,该变通办法允许将其转换为文本并将其流式传输到STDOUT,您可以在其中通过常规的grep
调用管道:
pdftotext SPECIFIC-FILE.pdf - | grep -Pzo "(?s)YOUR\s+QUERY"
这使得无法有效地使用glob,但是您至少可以迭代glob:
for pdf in *.pdf; do echo -n "$pdf:"; pdftotext "$pdf" - | grep -Pzo "(?s)YOUR\s+QUERY"; done
请注意,如果要匹配空白,启用\s+
后,几乎总是要使用-z
,它也与换行符匹配。有关标志的说明,请参见this other answer。