Quickly find and print all files in a folder, recu

2019-08-19 02:21发布

问题:

Consider the following folder structure starting in some root folder

/root/
/root/.git
/root/node_modules
/root/A/
/root/A/stuff1/
/root/A/stuff2/
/root/A/node_modules/
/root/B/
/root/A/stuff1/
/root/A/stuff2/
/root/B/node_modules/
...

Now I am in /root and I'd like to find all my own files inside it. I have a small number of my own files and the huge number of files inside node_modules and .git.

Because of that, traversing node_modules and filtering it out is unacceptable, as it takes too much time. I want the command to never enter the node_modules or .git folder.

回答1:

For excluding files only directly from the folder of the search:

find . -not \( -path './.git' -prune \) -not \( -path './node_modules' -prune \) -type f

If you want to exclude certain paths that are in subfolders, you can do that too using * wildcard.

Say you have node_modules too inside stuff1 and stuff2, and additionally dist and lib folders:

find . -not \( -path './.git' -prune \) -not \( -path './node_modules' -prune \) -not \( -path './*/node_modules' -prune \) -not \( -path './*/dist' -prune \)  -not \( -path './*/lib' -prune \) -type f

Tested on Windows using git bash 1.9.5

It seems however it does not work properly on Windows when a filter like -name '*.js' is passed. The workaround could be to not use -name and pipe to grep instead.

Kudos to @Daniel C. Sobral



标签: shell find