HelloPablo
HelloPablo

Reputation: 625

Reduce result of `find` to top level results

I have a find expression looking for node_modules directories. Some of the results are node_modules directories within a parent node_modules directory.

I'm only interested in finding the top most node_modules directory and performing an action on it, i.e. add a .metadata_never_index file so that Spotlight (macOS) doesn't index it.

I'm struggling to find a solution which deals with this; can find do this for me, or do I need to calculate it manually (maybe through string manipulations)?

As a bonus, I'd like to ignore all folders which already contain the .metadata_never_index file, if possible.

EDIT: Some context; this will run as a cron job and periodically look for node_modules in my ~/Sites directory, i.e multiple top-level projects.

Upvotes: 2

Views: 121

Answers (2)

HelloPablo
HelloPablo

Reputation: 625

After a bit more searching, I found a solution on SuperUser.

To summarise Paxali's answer:

find /home/code -type d -name ".git" | grep -v '\.git/'

In english: find me all directories named ".git" and filter out any occurences in the resultlist which contain ".git/" (dot git slash).

Except in my case, I used node_modules/ instead of .git/.

My working code:

find -f ~/Sites . -name node_modules | grep -v 'node_modules/' | while read fname; do
    touch $fname/.metadata_never_index
done

Upvotes: 2

Tal Avissar
Tal Avissar

Reputation: 10304

Find the top most modules can be found by using

npm command with flag --depth

npm list --depth=0

you can also create aliases as follows:

alias ng="npm list -g --depth=0 2>/dev/null"
alias nl="npm list --depth=0 2>/dev/null"

Upvotes: 0

Related Questions