Linux find 和 grep 命令一起使用

我试图找到一个命令或创建一个 Linux 脚本,可以执行这两个命令并列出输出

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...

有什么想法吗?

187305 次浏览

You are looking for -H option in gnu grep.

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

Here is the explanation

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

Now that the question is clearer, you can just do this in one

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

With relevant flags

   -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).

Or maybe even easier

grep -R put **/*bills*

The ** glob syntax means "any depth of directories". It will work in Zsh, and I think recent versions of Bash too.

grep -l "$SEARCH_TEXT" $(find "$SEARCH_DIR" -name "$TARGET_FILE_NAME")