【问题标题】:Filenames are lost when I find multiple pdf files, xarg pdftotext, and grep pattern当我找到多个 pdf 文件、xarg pdftotext 和 grep 模式时,文件名丢失
【发布时间】:2015-07-01 20:59:17
【问题描述】:

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

我从这里偷了下面的sn-p

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

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

它不必是“单线”。

谢谢。

【问题讨论】:

  • 管道不行,你必须写一些循环。

标签: bash pdf grep find xargs


【解决方案1】:

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

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="$1"

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

【讨论】:

  • 试过了,它会打印出所有文件名。我可以打印至少有一个匹配项的文件吗?
  • 是的,这很好。 grep 之后的一个简单 && 命令可以做到这一点。已编辑。
【解决方案2】:

为什么不使用类似的东西

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 个并行进程的输出可能会混合。

【讨论】:

    猜你喜欢
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    相关资源
    最近更新 更多