2

I'm using ubuntu linux, and I use bash from with a terminal emulator every day for many tasks.

I would like to know how to find a string or a substring within a file that is within a particular directory.

If I was knew the file which contained my target substring, I would just cat the file and pipe it through grep, thus:

cat file | grep mysubstring

But in this case, the pesky substring could be anywhere within a known directory.

How do I hunt down my substring ?

1
  • 1
    just as a note... you don't have to pipe cat to grep. grep can read files just fine. May 5, 2010 at 22:46

6 Answers 6

11

Use a shell wildcard:

grep mysubstring *

If you want to search subdirectories, use the -r option to recurse into them:

grep -r myssubstring .
1
  • or grep -r mysubstring directory May 5, 2010 at 22:49
4
find -type f | xargs grep mysubstring

These commands (find, xargs and grep) have lots of options, so you can tune this operation substantially.

1
  • add -print0 to find and -0 to xargs if your files/directories may have spaces in their names: find -type f -print0 | xargs -0 grep mysubstring May 3, 2010 at 15:41
4

say I want to find all the python code files that contain the text "wiki" under the directory "~/projects", here is the script:

grep -lir "wiki" ~/projects/**/*.py

adjust the script to your specific requirements.

2

No matter how you do it, don't cat files into grep. Your original version of

cat file | grep mysubstring

is more correctly done as

grep mysubstring file
2
  • 1
    although you're right this isn't an actual answer to the question. May 5, 2010 at 22:48
  • Why are you telling me this? May 6, 2010 at 17:22
1

If you don't need to do it in batch mode, you could install midnight commander (mc), it can search for strings in files.

1

If you want to find all files with a certain String recursive from "current" dir, use:

find . -type f -exec grep -l mysubstring {} \;

(should work on most *nix')

You must log in to answer this question.