Linux find 和 grep 命令一起使用
Posted
技术标签:
【中文标题】Linux find 和 grep 命令一起使用【英文标题】:Linux find and grep command together 【发布时间】: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
...
【参考方案1】:
您正在 gnu grep 中寻找 -H
选项。
find . -name '*bills*' -exec grep -H "put" \;
这里是解释
-H, --with-filename
Print the filename for each match.
【讨论】:
【参考方案2】:现在问题更清楚了,您可以在一个 grep 中做到这一点
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")
【讨论】:
以上是关于Linux find 和 grep 命令一起使用的主要内容,如果未能解决你的问题,请参考以下文章