【问题标题】:Linux find and grep command togetherLinux find 和 grep 命令一起使用
【发布时间】:2014-03-12 21:38:38
【问题描述】:

我正在尝试查找一个命令或创建一个 Linux 脚本来执行这两个命令并列出 otuput

find . -name '*bills*' -print

这会打印所有文件

./may/batch_bills_123.log
./april/batch_bills_456.log
..

从这个结果我想对一个单词做一个 grep 我现在手动做这个

grep 'put' ./may/batch_bill_123.log 

得到

sftp > put oldnet_1234.lst

我希望得到文件名及其匹配项。

./may/batch_bills_123.log   sftp > put oldnet_1234.lst
..
..
and so on... 

有什么想法吗?

【问题讨论】:

  • find . -name '*bills*' -exec grep put {} \;
  • 甚至find . -name "*bills*" -print0 | xargs -0 grep put...

标签: bash grep find


【解决方案1】:

您正在 gnu grep 中寻找 -H 选项。

find . -name '*bills*' -exec grep -H "put" {} \;

这里是解释

    -H, --with-filename
      Print the filename for each match.

【讨论】:

    【解决方案2】:

    现在问题更清楚了,您可以在一个 中做到这一点

    grep -R --include "*bills*" "put" .
    

    带有相关标志

       -R, -r, --recursive
              Read  all  files  under  each  directory,  recursively;  this is
              equivalent to the -d recurse option.
       --include=GLOB
              Search only files whose base name matches GLOB  (using  wildcard
              matching as described under --exclude).
    

    【讨论】:

    • 使用--include的好方法,但是当我运行--include选项中没有匹配的命令时,它提示Too many levels of symbolic links,切换到-R-r,得到同样的错误.
    • @BMW 有趣,无法复制,但听起来它已经达到了一些它不满意的符号链接阈值。有点惊讶这将是递归选项的默认行为。
    【解决方案3】:

    或许更简单

    grep -R put **/*bills*
    

    ** glob 语法表示“任意深度的目录”。它可以在 Zsh 中运行,我认为 Bash 的最新版本也是如此。

    【讨论】:

    • 根据你有多少匹配的文件,你可能会得到zsh: argument list too long: grep
    【解决方案4】:
    grep -l "$SEARCH_TEXT" $(find "$SEARCH_DIR" -name "$TARGET_FILE_NAME")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      • 1970-01-01
      • 2013-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多