1

Possible Duplicate:
Search for a text pattern in linux
Bash: is there a way to search for a particular string in a directory of files?

Let's say I am in a certain directory which contains a bunch of files, and I'm trying to look for the files that contain the string "string" within their content. Is there a way to do this? Thanks.

0

2 Answers 2

5

Simple answer:

grep -l string *

Will list all the files in your current directory that contain the string string.

And if you want to look for string in all the files in the current directory and any subdirectories, use:

grep -rl string .

Details:
* will match everything in your current folder except files that start with ., it will theoretically also match directories even though it usually doesn't matter much. If you want to be really picky you can use find like this:

find . -type f -maxdepth 1 -exec grep -i string {} /dev/null \;

If you want to look in the current folder and subfolders, leave -maxdepth 1 out like:

find . -type f -exec grep -i string {} /dev/null \;

{} means the filename it matches, but to liste the NAME of the file too you have to add atleast two filenames, and mentioning /dev/null does the trick. You can modify this as you like for wanted result. Should give you a base to work from. :)

3
  • just adding the -R switch will also mimic the described above behavior of find - if there's a need to do so by going through subdirs recursively. Commented Jan 7, 2012 at 19:09
  • -r and -R are the same thing to grep though. Commented Jan 7, 2012 at 19:10
  • yes, of course, it's just that you've edited your answer with the recursive example earlier than I managed to post on the original one that was missing it :) Commented Jan 7, 2012 at 19:12
1

Here are some ways to do it in current directory and all it's subdirectories.

If you want names of files where that text can be found:

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

If you want to see only lines where text was found:

find . -type f -exec grep 'string' {} \; 

If you wish to see names of files being searched and then content of lines when something gets found:

find . -type f -print -exec grep 'string' {} \;

Of course, this can be combined even further...

3
  • It should be -name '*', as file names without extensions do exist (and in fact are common on Unix). Commented Jan 7, 2012 at 19:04
  • To match files its usually better to use -type f to, possibly in combination with -name if you want to make deeper selection based on the filename itself. But usually -type f is enough for these needs. Commented Jan 7, 2012 at 19:11
  • There was no name filter specified, so I would remove it, but use -type f as suggested by @MattiasAhnberg. Commented Jan 13, 2012 at 8:11

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.