Goto each directory and subdirectories and grep the required pattern

Hi All,

I need your help in finding pattern from files present in different directories.

I need to search for a pattern "xyz" from "*.txt" files which are present in different levels of directories as shown.

example
-------

dir1/subdir1/file.txt
dir2/subdir2/subsubdir2/file.txt
dir3/subdir3/file.txt
dir4/subdir4/subsubdir4/subsubsubdir4/file.txt
..
..
..
dirn/...

If the pattern xyz is found in dir2... and dir3.. then i want the result saved as shown.

result.txt
---------
dir2/subdir2/subsubdir2
dir3/subdir3

The only static value is extension of file name (.txt) apart from this the directory names and file names can change in future.

Appreciate your help in Advance.

Thanks
imas.

something like..

find <path to where all the dir and sub dir exists> -name "*.txt" -type f 2>/dev/null | xargs grep -l 'xyz'

this will print the filenames if it matches the pattern.
you can get the dirname further and then unique values.

try this, not the exact output but closer to it

 
find /dir/to/search -name "*.txt" | xargs grep -l xyz

Thank you for the quick reply.

I will update you about the results tomorrow once i get back to my terminal.

-Regards,
imas

---------- Post updated 02-03-10 at 10:42 AM ---------- Previous update was 02-02-10 at 08:40 PM ----------

Hi,

This will give me the location of all the files.

find /dir/to/search -name "*.txt" | xargs grep -l xyz

But how do I write a script that will go into each directory and again search for another pattern from the *.txt file.

example
--------
if xyz pattern is found in the following directories.

dir2/subdir2/subsubdir2/file1.txt
dir3/subdir3/file2.txt
dir4/subdir4/subsubdir4/file3.txt

Please do not get confuse my actual requirement is to find the files in different directories which contains pattern xyz

Then go to each of the directories where you found xyz pattern in that file and again search for 2nd pattern from this file.

Appreciate your help.

Thanks
imas

you want to grep the second pattern in the "first pattern found files" or in all the files from the directories where at least one file having the first pattern exists. ?

Hi Khare,

Yes you are correct.

After the finding my 1st pattern I just need to cat each of the result using for loop and grep for my required 2nd pattern and get the required result.

Thank you very much.

PS: Neo/moderator please close this thread.

-imas.