Bash – How to find files in directories listed in a file

bashdirectory-structurefind

In a directory there are several subdirectories, something like:

TopLevelDir
+-- SubDir1
+-- SubDir2
+-- SubDir3
+-- SubDir4
+-- SubDir5
+-- SubDir6

I need to find files containing some specific text in a specific subset of those subdirectories. What is needed can be accomplished with:

find SubDir1 SubDir2 SubDir4 -type f -exec grep -H "desired text" {} \;

A similar search will be needed frequently. To save time and typing, I would like to store the names of the subdirectories to be searched in a file and use that when I run the find command next time, something like:

find subdirs2search.txt -type f  -name="*.txt" -exec grep -H "desired text" {} \;

Searching the web, checking man pages, and even checking my *nix book hasn't turned up anything on how to do this.

Is this possible? If so, how can it be done?

Best Answer

If the directory names are one-per-line, then you could avoid issues with directories that have spaces or tabs or wildcard characters in their names by using readarray (bash v4+):

readarray -t dirs < subdirs2search.txt
find "${dirs[@]}" ...

That would still not help if some directory names start with -, but with GNU find, there's no way around that.