1

I have the following folder structure:

example/
├── bar/
│   ├── 1
│   ├── 2
│   ├── 3
│   ├── 4
│   ├── 5.txt
│   ├── bar.mylib/
│   │   ├── 1
│   │   ├── 2
│   │   ├── 3
│   │   ├── 4
│   │   ├── 5
│   │   ├── 6
│   │   └── foo/
│   │       ├── 1
│   │       ├── 3
│   │       └── 5
│   └── foo.mylib
└── foo/
    ├── 1
    ├── 3
    ├── 5
    └── node_modules/
        ├── 1
        ├── 2
        ├── 3
        ├── 4
        └── 5

5 directories, 23 files

I want to build a find command that would list all the files and directories, but excluding specific directory name patterns, without entering in those directories at all, but still include the directory names in the output.

The following output is expected:

example/
example/foo/
example/foo/3
example/foo/5
example/foo/1
example/foo/node_modules/
example/bar/
example/bar/5.txt
example/bar/3
example/bar/4
example/bar/1
example/bar/bar.mylib/
example/bar/foo.mylib
example/bar/2

I tried the following:

find . -type f ! -path '*/*.mylib/*' ! -path '*/node_modules/*'

This kind of works, but it seems to enter in those directories that are ignored. Also, it is not listing the ignored directories (namely example/foo/node_modules/ and example/bar/bar.mylib/).

I intentionally have two .mylib paths: one is directory and the other is a file. I want to list both, but ignore the content of the directory.

How can we do this with find?

1 Answer 1

3

The strategy is to prune all directories matching your node_modules or *.mylib (prune means to not descend into them) and print all other files.

find . -print \( -type d \( -name 'node_modules' -o -name '*.mylib' \) -prune \)

Consult Find's specification or the manual if any of the above options is foreign to you.

2
  • Amazing! Thank you so much. I would like to add the trailing / after the directory paths if it is easy. Jan 3, 2021 at 13:52
  • @IonicăBizău You are welcome. Yeah, that doesn't work because the found directories do not get the final /. GNU Find even warns me that find: warning: -path node_modules/ will not match anything because it ends with /.
    – Quasímodo
    Jan 3, 2021 at 21:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .