Search code examples
linuxbashshelldirectory-listing

Opening directory without knowing its name


I'm writing a script in which user inputs the directory in which he wants to find a specific string inside .txt files, but I don't know how to open every directories inside the given directory without knowing their names.

For example this is a directory that the user specifies:

Project/
   AX/include/
             ax.txt
             bx.txt
   AX/src/
         ax.txt
         bx.txt
   BY/include/
             ay.txt
             by.txt
   BY/src/
         ay.txt
         by.txt

Solution

  • Just use grep -r to find strings in files recursively. You shouldn't reinvent the wheel. In your case run grep -r "string to find" Project/

    That said, to list the folders inside a folder path/to/folder/ you just need to let the shell expand it with globbing like this ls path/to/folder/*/. So you just need to run yourcommand path/to/folder/*/

    Alternatively use find:

    find path/to/folder/ -type d -maxdepth 1 -exec yourcommand {} + # or
    find path/to/folder/ -type d -maxdepth 1 -print0 | xargs -z yourcommand
    

    To do that in more levels use find path/to/folder/ -type d -exec yourcommand {} +, or yourcommand path/to/folder/**/*/ after enabling globstar with shopt -s globstar