【问题标题】:how to cat on the results of a find operation + bash如何对查找操作+ bash的结果进行分类
【发布时间】:2015-10-18 10:29:15
【问题描述】:
$ a=$(find . -iname 'app.conf' 2>/dev/null)

上面给了我一个如下所示的文件列表:

$ echo "$a"
./etc/apps/dashboard_examples/default/app.conf
./etc/apps/framework/server/apps/homefx/splunkd/default/app.conf
.
.
.

我怎样才能对这些文件中的每一个都做一个 cat,然后 grep? 我可以在数组中的第一个元素上做 cat 吗? cat a[1]?或者我如何将 a 放入像数组这样的格式?

【问题讨论】:

  • $a 变量的值不是数组。它是一个字符串。您不能安全地(面对名称中带有空格/换行符/等的文件)对 find 调用的结果进行安全操作。请参阅Bash FAQ 001,了解安全、正确地处理逐行数据的方法。另请注意,如果有用, find 可以-exec 对它找到的内容发出命令。

标签: arrays bash list find cat


【解决方案1】:

您可以使用myarray=( $(command) ) 表达式将find 的结果存储到一个数组中:

a=( $(find . -iname 'app.conf' 2>/dev/null) )
# ^                                         ^

然后,打印第一个元素:

echo "${a[0]}"

或者如果你想cat它,说:

cat "${a[0]}"

如果您想对每个结果执行命令,您可以使用 -exec,如 cmets 中的 Etan Reisner 所示:

find . -iname 'app.conf' -exec cat {} + 2>/dev/null
#                        ^^^^^^^^^^^^^^

【讨论】:

    【解决方案2】:

    我会使用xargs 来做大部分事情。

    find . -iname 'app.conf' 2>/dev/null |
      xargs grep somepattern
    

    可以使用-print0find-0xargs 安全地操作带有空格的文件名。

    更多信息请参见man xargs

    【讨论】:

      【解决方案3】:

      用for怎么样?

      > for a_file in $a; do cat $f | grep something; done
      

      【讨论】:

      • 对于名称中包含空格、换行符或 shell 元字符的文件不安全。
      • 我看了你的评论,发现“find exec”更加安全方便,谢谢!
      猜你喜欢
      • 2015-01-27
      • 2010-11-14
      • 1970-01-01
      • 2013-07-24
      • 2019-12-23
      • 2016-02-14
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多