5

How do I find a string contained in (possibly multiple) files in a folder including hidden files and subfolders?

I tried this command:

find . -maxdepth 1 -name "tes1t" -print0 | sed 's,\.\/,,g'

But this yielded no results.

ShellFish
  • 4,351
  • 1
  • 20
  • 33
user3382714
  • 185
  • 2
  • 4
  • 9

2 Answers2

4

grep -Hnr PATTERN . if your grep supports -r (recursive, = -d recurse). Note there would be no limit on recursion depths then.

Or try grep -d skip -Hn PATTERN {,.[!.]}*{,/{,.[!.]}*}; this should work since grep accepts multiple file arguments. Just throw away the -d skip stuff if your version of grep doesn't support it. For shells without the brace expansion, use the manually expanded form * */* */.[!.]* .[!.]* .[!.]*/* .[!.]*/.[!.]*.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Mingye Wang
  • 1,107
  • 9
  • 32
  • 2
    You don't need `extglob`. Just `grep PATTERN .[!.]* * */.[!.]* */*` where `[!.]` specifies "any character except `.`" (so as to prevent going into the parent directory `..`). – tripleee Jun 23 '15 at 03:22
  • Yes this is one sick answer, great stuff! – ShellFish Jun 23 '15 at 08:08
0

First of all, your maxdepth should have been 2 instead of 1, now your command won't descend in subdirectories. Furthermore you can simply for your pattern on the output of find. This can be achieved as follows:

find . -maxdepth 2 -type f -exec grep 'pattern here' '{}' \;

Explanation:

  • find . execute find in current directory.
  • -maxdepth 2 descend in subdirectories by no further.
  • -type f find every file that is not a directory.
  • -exec grep 'pattern' '{}' execute a grep statement with a certain pattern, the {} contains the filename for each file found.

Add options to grep for color highlighting, outputting line numbers and/or the file name.

For more information see man find and man grep.

ShellFish
  • 4,351
  • 1
  • 20
  • 33
  • Or possibly you should not have `-maxdepth` at all if the intent is to traverse subdirectories of subdirectories recursively. The question is not really clear on this. – tripleee Jun 23 '15 at 03:19
  • @tripleee true, I just figured the OP wanted to limit the recursion level because he included the option. I will add your remark to the answer, thanks for pointing that out! – ShellFish Jun 23 '15 at 08:06