Search with "grep" for folder names

When using grep you can search for a specific regex, but only inside of a file. Is there any way, I can search for a folder name?

6 Answers

I usually use find:

$ find . -name 'FolderBasename*' -type d

or for more complex queries

$ find . -regex '{FolderRegex}' -type d

As pointed out in the comments if you want case insensitive searches do -iname and -iregex

3

If you really mean regexp instead of shellglob, you may want to use

find <path> -regex <regex> -type d

eg.

find Code/ -E -regex '(bin|redblack)_tree\.hs' -type d

the option -E turns on extendend regexp, see man find for more.

If you are just concerned with matching the name you can simply use '-name' in find.

find <path> -name '<regex>' -type d

find is far better but a clunky answer to your question:

ls -l | grep '^d'
1

Another answer, which works without using regex (and Bash4: shopt -s globstar):

ls **/dirname/ -d

(based on recursive globbing: **/ and matching only folders /*/)

0

I created a script file called dsearch (directory search) to do this:

# !/bin/bash
# search all folders from the current folder for a foldername
foldername=$1
find . -name "*$foldername*" -type d

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like