终端 - 将查找与 xargs 相结合 - 在右侧查找

terminal - combining find with xargs - find on the right side

有一个名为 keywords.txt,

的纯文本文件

对于 keywords.txt 中的每个 WORD,我想在当前目录中找到包含该 [=30] 的所有文件名=]WORD

cat keywords.txt | xargs find . -name

错误 Mac:

find: xxx: unknown primary or operator

错误 Ubuntu:

find: paths must precede expression: xxx
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec|time] [path...] [expression]

问题:

  1. 如果你能告诉我错误发生的原因,如何解决它,那就太好了?
  2. 我想将模式传递给 find 以便我可以找到包含 WORD 的每个文件名,该怎么做?

    cat keywords.txt | xargs find . -name {*WORD*}
    

我搜索了google,大部分用例:

在左边找到,在右边找到xargs,不是我期望的答案。

错误发生是因为 xargs 在给定命令的末尾添加了多个单词,导致 find 调用可能看起来像

find . -name string1 string2 string3 etc.

以下简短的 shell 脚本将查找所有文件(无论类型如何),这些文件在其文件名的任何位置包含其命令行中给出的任何字符串:

#!/bin/sh

# construct options for 'find' that matches filenames using multiple
# -o -name "*string*"
for string do
    set -- "$@" -o -name "*$string*"
    shift
done

# there's a -o too many at the start of $@ now, remove it
shift

# add e.g. -type f to only look for regular files
find . '(' "$@" ')'

您可以从 xargs:

xargs -n 100 ./script.sh <keywords.txt

由于脚本使用扩展命令行调用 find,为了安全起见,我已将允许调用脚本的字符串数量限制为 100。

请注意,这将拆分 keywords.txt 中包含空格的字符串。