108

I am trying to find a command or create a Linux script that can do this two commands and list the output

find . -name '*bills*' -print

this prints all the files

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

from this result I want to do a grep for a word I do this manually right now

grep 'put' ./may/batch_bill_123.log 

and get

sftp > put oldnet_1234.lst

I would hope to get the file name and its match.

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

do you have any ideas?

2
  • 3
    find . -name '*bills*' -exec grep put {} \;
    – devnull
    Commented Feb 13, 2014 at 19:40
  • 2
    Or even find . -name "*bills*" -print0 | xargs -0 grep put...
    – twalberg
    Commented Feb 13, 2014 at 20:02

4 Answers 4

162

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.
1
  • 1
    The nice thing about using grep with find is you can set -maxdepth on find, which you can't when just using grep -R.
    – jschmitter
    Commented Apr 19, 2022 at 13:41
71

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).
2
  • 1
    Good way to use --include, but when I run the command with no match in --include option, it prompts Too many levels of symbolic links, switch to -R and -r, get same error.
    – BMW
    Commented Feb 13, 2014 at 21:21
  • @BMW Interesting, can't replicate, but sounds like it's reaching some symlink threshold that it's not happy about. A bit surprised that would be default behavior for a recursive option. Commented Feb 13, 2014 at 21:31
12

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.

2
  • 2
    Depending on how many matched files you have, you might get zsh: argument list too long: grep
    – Sarke
    Commented Jan 21, 2021 at 15:49
  • In bash you need to enable it first. shopt -s globstar
    – Slawa
    Commented Dec 12, 2022 at 11:46
5
grep -l "$SEARCH_TEXT" $(find "$SEARCH_DIR" -name "$TARGET_FILE_NAME")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.