1

I'm trying to find/extract directories based on an expression that applies to the file path. For example, I used the command:

find . -type d -links 2

To get a list of directories that looks something like this:

./foo/ABC/W
./foo/ABC/X
./foo/ABC/Y
./foo/ABC/Z
./foo/BCD/W
./foo/BCD/X
./foo/BCD/Y
./foo/BCD/Z
./foo/CDE/W
./foo/CDE/X
./foo/CDE/Y
./foo/CDE/Z
./bar/CDE/V
./bar/CDE/Q
./bar/BCD/V
./bar/BCD/Q
./bar/ABC/V
./bar/ABC/Q

I'm wondering how to take this list, and extract only filepaths containing say, "CDE" in them:

./foo/CDE/W
./foo/CDE/X
./foo/CDE/Y
./foo/CDE/Z
./bar/CDE/V
./bar/CDE/Q

This is what I've tried so far, which outputs nothing when I try it:

find . -type d -links 2 -name "CDE" -print
5
1
$ find . -type d -links 2 -path '*CDE*'
./foo/CDE/X
./foo/CDE/Z
./foo/CDE/W
./foo/CDE/Y
./bar/CDE/Q
./bar/CDE/V

Or use

find . -type d -links 2 -path '*/CDE/*'

if you know CDE is the name of a subdirectory somewhere in the middle of the paths you're looking for.

1
  • Ah thanks! Knew it was something minor like that! – bactro Jul 21 '20 at 19:07
0
find . -type d -links 2 -name "CDE" -print

matches directories whose basename is exactly CDE (because of -name CDE) and that have no child directories (because of -links 2).

The basename of a file is just the bit after the last / of its path. For instance, the basename of ./foo/CDE/W is W. From this you see that none of the directories matches both conditions.

You are after

find . -type d -links 2 -path '*/CDE/*'

The -path pattern option is true if

the current pathname matches pattern using the pattern matching notation described in Pattern Matching Notation.

In the "Pattern Matching Notation", the asterisk matches any string.

As a last note, -print is used by default unless -ok or -exec are present, so you can drop it.

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