1

Say I have the following tree:

root:
d foo 
d bar

/foo:
d A
- tmp.txt

/bar:
d B
- tmp2.txt

/foo/A:
- tmp3.txt

/bar/B:

d = directory and - = file

I need to answer the following question: which directory (excluding the root) contains the least entries?

I have tried

  find . | grep -oE '/([a-zA-Z]+/)+'

to get the number of occurrences for each directory. The problem is this command exclude empty directories, in this case /bar/B is excluded.

Any guidance on how to solve this would be appreciated.

5

With GNU tools:

find . -printf '%h\0' -type d ! -name . -print0 |
  sort -z |
  uniq -zc |
  sort -zn |
  sed -z q |
  tr '\0' '\n'

If you can guarantee that file names won't contain newline characters, you can simplify it to:

find . -printf '%h\n' -type d ! -name . -print | sort | uniq -c | sort -n | head -n1

(the number reported is the number of files in the directory minus 1 (. is counted, but not ..)).

With zsh:

count() {
  set -- $REPLY/*(NDoN)
  REPLY=$#
}
print -r -- **/*(Do+count[1])
1

You could use something like this:

find . -type d -exec sh -c \
    'printf -- "%-20s: " {};
    find {} -maxdepth 1 -type f -printf "%i\n" | wc -l' \;

If you have this tree, (tree is a nice command btw.):

$ tree -a .
.
├── bar
│   ├── B
│   └── tmp2.txt
├── ff
├── .ff.swp
└── foo
    ├── A
    │   └── tmp3.txt
    ├── f2.txt
    ├── f3.txt
    └── tmp.txt

You get this:

.                   : 2
./foo               : 3
./foo/A             : 1
./bar               : 1
./bar/B             : 0

To list one of the lesser (more then one could have e.g. null files), one could do something like:

find . -type d -exec sh -c \
    'find "{}" -maxdepth 1 -type f -printf "%i\n" | \
    wc -l | xargs printf "%-2d";
    printf ": %s\n" "{}" ' \; | sort -k1,1 | head -n 1

if folders does not contain newline.


If -maxdepth is not available, an alternative could be:

find . -type d -exec sh -c \
    'printf -- "%-20s: " "{}";
    find "{}" ! -wholename "{}" -prune -type f -printf "%i\n" | wc -l' \;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.