Home > Enterprise >  Linux CLI: List top level directories with zero files
Linux CLI: List top level directories with zero files

Time:12-16

I need a list of top-level directories with zero files. Specifically, they can contain subdirectories provided they are empty. Here's what I've tried and the issues with each:

find . -maxdepth 1 -type d -empty

This does not show directories with subdirectories -- also with zero files.

It skips structures like the following: Top-level-dir ( 0 files ) => 2nd-level dir ( 0 files )

find . -type f | cut -d/ -f2 | sort | uniq -c | sort -nr

The above line is great but it skips empty top-level directories containing subdirectories -- if those subdirs are empty as well. I should see all top-level directories in the output and I'm only seeing directories with files. I'm looking for a solution that will print directories with 0 files in addition to the file count of other top-level directories.

The correct solution will include top-level directories with 0 files -- even if they contain subdirectories, provided all subdirectories contain 0 files as well.

Example output:

  • dir1 0
  • dir2 5
  • dir3 0
  • dir4 26

...etc.

CodePudding user response:

I think this does what you want:

find * -maxdepth 0 -type d \
  -exec sh -c 'echo -n "{}: "; find "{}" -type f -print | wc -l' \;

find * -maxdepth 0 -type d generates a list of top-level directories. For each directory, we run the command passed as the argument to -exec. In this command ,{} is substitute by the name of a directory.

Output will look something like:

./dir1: 0
./dir2: 2
./dir3: 33
./dir4: 0
./dir5: 62

Etc.

  • Related