Under *nix, how can I find a string within a file within a directory?

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 ?

roberto

Posted 2010-05-02T10:29:58.053

Reputation:

1just as a note... you don't have to pipe cat to grep. grep can read files just fine. – xenoterracide – 2010-05-05T22:46:57.487

Answers

11

Use a shell wildcard:

grep mysubstring *

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

grep -r myssubstring .

outis

Posted 2010-05-02T10:29:58.053

Reputation: 388

or grep -r mysubstring directory – xenoterracide – 2010-05-05T22:49:01.490

4

find -type f | xargs grep mysubstring

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

Marcelo Cantos

Posted 2010-05-02T10:29:58.053

Reputation: 1 321

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 – 2010-05-03T15:41:13.583

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.

Zhang Yining

Posted 2010-05-02T10:29:58.053

Reputation: 141

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

Andy Lester

Posted 2010-05-02T10:29:58.053

Reputation: 1 121

1although you're right this isn't an actual answer to the question. – xenoterracide – 2010-05-05T22:48:12.680

Why are you telling me this? – Andy Lester – 2010-05-06T17:22:32.710

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.

geek

Posted 2010-05-02T10:29:58.053

Reputation: 7 120

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

Sverre Marvik

Posted 2010-05-02T10:29:58.053

Reputation: 361