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


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

find . -name 'node_modules' -prune


$ 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'
$ find . -name 'node_modules' -prune

You must log in to answer this question.

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