How to recursively delete the contents of all "node_modules" directories (or any dir), starting from current directory, leaving an empty folder?

Suppose I have a directory structure like this:

projects/
  project1/
    src/
    node_modules/
      dir1/
      dir2/
      dir3/
      file
  project2/
    node_modules/
      dir4/

Starting from projects/ I want to delete the contents of all node_modules/ directories, but I do not want to delete the node_modules/ itself, leaving it empty, without folders or files inside.

In the example above the items dir1, dir2, dir3, file and dir4 would be deleted.

Asked By: Lawrence

||

The following will delete all files and directories within a path matching node_modules:

find . -path '*/node_modules/*' -delete

If you would like to check what will be deleted first, then omit the -delete action.

Answered By: Stephan
Categories: Answers Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.