11

In my dev root directory I'd like to find all node_modules directories. The problem is that node_modules itself contains subdirectories named node_modules. How can I find only the top node_modules folder? I tried:

find -iname "node_modules" | grep -P 'node_modules.*(?!node_modules)'

But it doesn't filter the subdirectories.

1 Answer 1

16

You need to "prune" node_modules directories from the search once they have been found:

find . -name 'node_modules' -prune

Example:

$ mkdir foo/{a,a/b,a/b/c,}/node_modules/{a,a/b,a/b/c,}/node_modules/ -p; cd foo
$ find . -name 'node_modules'
./a/b/c/node_modules
./a/b/c/node_modules/a/b/c/node_modules
./a/b/c/node_modules/a/b/node_modules
./a/b/c/node_modules/a/node_modules
./a/b/c/node_modules/node_modules
./a/b/node_modules
./a/b/node_modules/a/b/c/node_modules
./a/b/node_modules/a/b/node_modules
./a/b/node_modules/a/node_modules
./a/b/node_modules/node_modules
./a/node_modules
./a/node_modules/a/b/c/node_modules
./a/node_modules/a/b/node_modules
./a/node_modules/a/node_modules
./a/node_modules/node_modules
./node_modules
./node_modules/a/b/c/node_modules
./node_modules/a/b/node_modules
./node_modules/a/node_modules
./node_modules/node_modules
$ find . -name 'node_modules' -prune
./a/b/c/node_modules
./a/b/node_modules
./a/node_modules
./node_modules
0

You must log in to answer this question.

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