0

I want to get a list of files that contain a given text within my file-system. Furthermore only files should be considdered that are located in a directoy given by a pattern.

So let´s say I have a number of directories called myDir within my filelsystem as shown here:

/usr
  /myDir
/tmp
  /myDir
  /anotherDir

Now I want to get all the files within those directories that contain the text.

So basically I need to perform these steps:

  1. loop all directories names myDir on the whole file-system
  2. for every directory within that list get the files that contain the search-string

What I tried so far is find /etc /opt /tmp /usr /var -iname myDir -type d -exec ls -exec grep -l "SearchString" {} \;

However this doesn´t work as the results of find are directories which I may not use as input for grep. I assume I have to do one step in between the find and the grep but can´t find out how to do this.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • Have you checked [Finding all files containing a text string on Linux](http://stackoverflow.com/q/16956810/1983854)? – fedorqui Nov 06 '15 at 11:22
  • Sure, but that takes much time and I want to simpliyfy this a bit by providing some information on the folders to be used for the search. – MakePeaceGreatAgain Nov 06 '15 at 11:23
  • `find /path1 /path2 -type f -exec grep -H "your string" {}\;` should suffice. – fedorqui Nov 06 '15 at 11:32
  • @fedorqui The problem is I do not know the (absolute paths to the ) directories where the files are located, only their names. Thus `path1` could be `/usr/path1` or even `/etc/someotherdir/myDir`. – MakePeaceGreatAgain Nov 06 '15 at 11:35
  • OK, so you want to find files in directories the name of which you know, but not where exactly they are placed. Then, if you don't know more than that you have to look for everything from `/`. – fedorqui Nov 06 '15 at 11:39
  • @fedorqui This works however if I perform this query either it takes so much time that I do not recognize it´s actually working or it breaks after some hits without doing any further - not sure. This is why I looked for another way that might be a bit faster then searching the entire file-system – MakePeaceGreatAgain Nov 06 '15 at 11:41
  • I understand. However, you need other patterns to filter on if you want to filter on : ) What else can be shared among these directories? – fedorqui Nov 06 '15 at 11:48

1 Answers1

1

I think I got it and will show you a little script that achieves what I need:

for i in $(find / -type d -iname myDir) do
    for j in $(find "$i" -type f) do         
        grep "SearchString" "$j"
    done
done

This will give me all the files that contain the SearchString and are located in any of the folders named myDir.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111