如何在变量前后用通配符包围 find 的 -name 参数?

How to surround find's -name parameter with wildcards before and after a variable?

我有一个换行符分隔的字符串列表。我需要遍历每一行,并使用用通配符包围的参数。最终结果会将找到的文件附加到另一个文本文件。这是我到目前为止尝试过的一些方法:

cat < ${INPUT} | while read -r line; do find ${SEARCH_DIR} -name $(eval *"$line"*); done >> ${OUTPUT}

我已经尝试了 eval/$() 等的多种变体,但我还没有找到一种方法来保留两个星号。大多数情况下,我得到类似于 *$itemFromList 的内容,但它缺少第二个星号,导致找不到文件。我认为这可能与 bash 扩展有关,但到目前为止我还没有找到任何资源。

基本上,需要为 -name 参数提供类似于 *$itemFromList* 的内容,因为该文件在我要搜索的值前后都有单词。

有什么想法吗?

使用双引号防止星号被解释为 shell 而不是 find.

的指令
-name "*$line*"

因此:

while read -r line; do
  line=${line%$'\r'}  # strip trailing CRs if input file is in DOS format
  find "$SEARCH_DIR" -name "*$line*"
done <"$INPUT" >>"$OUTPUT"

...或者,更好:

#!/usr/bin/env bash

## use lower-case variable names
input=
output=

args=( -false )                 # for our future find command line, start with -false
while read -r line; do
  line=${line%$'\r'}            # strip trailing CR if present
  [[ $line ]] || continue       # skip empty lines
  args+=( -o -name "*$line*" )  # add an OR clause matching if this line's substring exists
done <"$input"

# since our last command is find, use "exec" to let it replace the shell in memory
exec find "$SEARCH_DIR" '(' "${args[@]}" ')' -print >"$output"

注:

  • shebang 指定 bash 确保扩展语法(例如数组)可用。
  • 有关为什么数组是用于收集命令行参数列表的正确结构的讨论,请参阅 BashFAQ #50
  • 有关POSIX环境规范和shell变量命名约定,请参阅http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html第四段:所有大写名称用于对[=]有意义的变量36=] 本身,或 POSIX-指定的工具;小写名称保留供应用程序使用。你写的那个剧本?就规范而言,它是一个应用程序。