Find all directories that contain a certain character and print them out

10

3

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

Devid Demetz

Posted 2017-06-11T11:32:56.013

Reputation: 105

Answers

18

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

Yaron

Posted 2017-06-11T11:32:56.013

Reputation: 534

2

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 – 2017-06-11T11:53:11.133

@KamilMaciorowski - thanks for the comment – Yaron – 2017-06-11T11:54:15.957

@DevidDemetz - great :-) – Yaron – 2017-06-11T11:58:38.833

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 – 2017-06-11T12:40:51.550

@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 – 2017-06-11T12:49:48.160

On MacOS it doesn't work when you leave out the path. find . -name "*c*" -type d worked for me. – Gigo – 2018-08-27T17:49:12.513

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.

phuclv

Posted 2017-06-11T11:32:56.013

Reputation: 14 930