List of all directories that do not contain subdirectories

I have a solution for my question

find . -type d -exec sh -c 'test $(find "$0" -maxdepth 1 -type d | wc -l) -eq 1' {} \; -print 

I wonder if there is a better (faster) method for this. I don’t really like to start with a β€œsearch” of another search process.

+4
source share
2 answers

With fewer encodings, the following commands should also work:

 find . -type d|awk 'NR>1{a[c++]=$0; t=t $0 SUBSEP} END{for (i in a) {if (index(t, a[i] "/") > 0) delete a[i]} for (i in a) print a[i]}' 

Make it more readable:

 find . -type d | awk 'NR > 1 { a[c++]=$0; t=t $0 SUBSEP } END { for (i in a) { if (index(t, a[i] "/") > 0) delete a[i]} for (i in a) print a[i] }' 

Although there may be more code in this solution, this awk-based command should work much faster in a large directory than the find | wc find | wc , as in the question.

Performance Testing:

I ran it in a directory containing 15k + subdirectories, and found this awk command much faster (250-300% faster) than the OP find | wc find | wc .

+1
source

man find parameter will be specified:

  -links n File has n links. 

You are looking for directories containing only two links (namely . And name). The following directories will return directories without subdirectories:

 find . -type d -links 2 

Each directory in a normal Unix file system has at least 2 hard links: its name and its entry . (parent directory). In addition, in its subdirectories (if any) there is an entry .. associated with this directory.

+4
source

Source: https://habr.com/ru/post/1493426/


All Articles