2

Consider path in a directory structure

/A/B/C/D
/A/B/C/E
/A/B/O/P

now if I want to list all path which has sub directory C in it, then can it be done through grep? Expected output:

/A/B/C/D
/A/B/C/E

I tried using grep and find but could not achieve this.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

2 Answers2

4

While ka3ak's answer works, find comes with a parameter "-path" so you can simply use

find . -type d -path "*/c/*"

-path seems also a bit faster:

[hexathos:~/test] $ time find . -regextype posix-extended -regex ".*/c/.*"
./a/b/c/d
./a/b/c/e

real    0m0,013s
user    0m0,010s
sys 0m0,000s
[hexathos:~/test] $ time find . -type d -path "*/c/*"
./a/b/c/d
./a/b/c/e

real    0m0,012s
user    0m0,007s
sys 0m0,003s
0

You only need find for this:

find A -type d -regextype posix-extended -regex ".*/C/.*"

For the following directory structure

A                                                                                                                                                                                                                  
└── B                                                                                                                                                                                                              
    ├── C                                                                                                                                                                                                          
    │   ├── D                                                                                                                                                                                                      
    │   └── E                                                                                                                                                                                                      
    ├── C1                                                                                                                                                                                                         
    │   └── E                                                                                                                                                                                                      
    └── O
        └── P

it would return:

A/B/C/E
A/B/C/D
ka3ak
  • 1,255