Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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 ?

share|improve this question

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
add comment

6 Answers

Use a shell wildcard:

grep mysubstring *

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

grep -r myssubstring .
share|improve this answer
    
or grep -r mysubstring directory –  xenoterracide May 5 '10 at 22:49
add comment
find -type f | xargs grep mysubstring

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

share|improve this answer
    
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
add comment

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.

share|improve this answer
add comment

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
share|improve this answer
    
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
add comment

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

share|improve this answer
add comment

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.