Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Linux CLI: List top level directories with zero files

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 )

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading