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 ?

migrated from stackoverflow.com May 2 '10 at 16:49

This question came from our site for professional and enthusiast programmers.

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

Use a shell wildcard:

grep mysubstring *

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

grep -r myssubstring .
  • or grep -r mysubstring directory – xenoterracide May 5 '10 at 22:49
find -type f | xargs grep mysubstring

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

  • 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 – Doug Harris May 3 '10 at 15:41

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.


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
  • 1
    although you're right this isn't an actual answer to the question. – xenoterracide May 5 '10 at 22:48
  • Why are you telling me this? – Andy Lester May 6 '10 at 17:22

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


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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy