当我找到多个 pdf 文件、xarg pdftotext 和 grep 模式时,文件名丢失

Filenames are lost when I find multiple pdf files, xarg pdftotext, and grep pattern

我想制作一个 shell 脚本来在 pdf 文件中搜索模式(让它们成为我自己的语料库!!)

我从这里偷了下面的片段

How to search contents of multiple pdf files?

find /path/to/folder -name '*.pdf' | xargs -P 6 -I % pdftotext % - | grep -C1 --color "pattern"

输出如下所示

--
--
small deviation of γ from the average value  0.33 triggers
a qualitative difference in the evolution pattern, even if the

我可以让这个命令打印文件名吗?

不必是 "one-liner"。

谢谢。

不多。只需将命令拆分成一个循环即可。

find /path/to/folder -name '*.pdf' | while read file
do
echo "$file"
pdftotext "$file" | grep -C1 --color "pattern" && echo "$file"
done

编辑:我刚刚注意到该示例包含一个并行 xargs 命令。这不是不可能在循环中解决。您可以将 pdftotext & grep 命令写入 function 然后使用 xargs

EDIT2:仅在匹配时打印出文件

它可能看起来像这样:

#!/bin/bash

files=$(find /path/to/folder -name '*.pdf')

function PDFtoText
{

file=""

if [ "$#" -ne "1" ]
then
    echo "Invalid number of input arguments"
    exit 1
fi

pdftotext "$file" | grep -C1 --color "pattern" && echo "$file"

}
export -f PDFtoText


printf "%s\n" ${files[@]} | xargs -n1 -P 6 -I '{}' bash -c 'PDFtoText "$@" || exit 255' arg0 {}

if [[ $? -ne 0 ]]
then
exit 1
fi

为什么不使用类似

的东西
find /path/to/folder/ -type f -name '*.pdf' -print0 | \
  xargs -0 -I{} \
  sh -c 'echo "===== file: {}"; pdftotext "{}" - | grep -C1 --color "pattern"'

它总是打印文件名。你认为这是一个可以接受的妥协吗?否则 echo 部分可以像之前建议的那样用 && 移动到 grep 之后。

我更喜欢将 -print0-0 结合使用,只是为了处理带空格的文件名。

我会删除 -P6 选项,因为 6 个并行进程的输出可能会混合。