13

I need to find all directories which contain a certain character in their name and print them out.

So if i have the directories:

abc cde fgh

And I search for "c" I should get:

abc 
cde
22

The following commands perform the required query:

find -name "*c*" -type d
  • starts with the current directory (no need to specify directory in case of current directory)
  • -name "*c*" - with name contains the letter c
  • -type d - which are a directory

You can run the command on other directory (/full/path/to/dir) using:

find /full/path/to/dir -name "*c*" -type d

More info nixCraft find command

5
  • 4
    Note: in this case -print is unnecessary, it's the default action. Also, to start with the current directory only, one may not give a path because . is the default path. Good answer though. Wildcards may be a trap like in this question, quoting them is very important here. – Kamil Maciorowski Jun 11 '17 at 11:53
  • @DevidDemetz - great :-) – Yaron Jun 11 '17 at 11:58
  • I have another question. If id now like to rename the the directory name. like the "c" that i searched for should become an "a". how would i do that – Devid Demetz Jun 11 '17 at 12:40
  • @DevidDemetz - if you have a new question - how to 1) find directories with specific pattern and 2) replace the directories name with a specific pattern - please open a new question for that. – Yaron Jun 11 '17 at 12:49
  • On MacOS it doesn't work when you leave out the path. find . -name "*c*" -type d worked for me. – Gigo Aug 27 '18 at 17:49
1

If globstar is enabled you can use this

for d in **/*c*/; do echo $d; done

The first ** will match any arbitrary subdirectory paths. Then *c*/ with match folders with the c character in it

If it's not enabled you can enable it with shopt -s globstar

  • globstar

    • If set, the pattern ** used in a filename expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a /, only directories and subdirectories match.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.