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.

Kaitlyn Mcmordie
  • 769
  • 1
  • 7
  • 20

2 Answers2

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. :)

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...

Josip Medved
  • 8,909