Search code examples
linuxbashmacosterminalfind

Find & List all directories under specific size in terminal? (Mac/Linux)


I'm trying to list all directories in my Music Library that are smaller than 5mb. I tried the following command in terminal:

find /volume1/Music\ Library/ -type d -size -5M -print;

But it just listed thousands of directories, and the few I checked were of course much larger than 5mb. To come up with this command, I modified another command I use often to find empty directories:

find /volume1/Music\ Library/ -type d -empty -print;

For this one, after I verify that it's correct, I replace -print; with -delete and am looking for a similar experience based around directory size. I do not want automatic deletion for (hopefully) obvious reasons.

I'm doing this in Terminal through SSH to my Synology NAS which is running a Linux-based OS.


Solution

  • According to the manual of find command, the -size argument only works for file:

           -size n[cwbkMG]
                  File uses n units of space.  The following suffixes can be used:
    

    With find, du and awk:

    find /volume1/Music\ Library/ -type d -exec du -ms {} \;| awk '$1 < 5'|cut -f 2-
    

    This will list all directories with total contents smaller than 5M.

    Edit:

    If you want to delete the expected directories, you could add | xargs -d \\n rm -rf to the end of the command line:

    find /volume1/Music\ Library/ -type d -exec du -ms {} \;| awk '$1 < 5'|cut -f 2- | xargs -d \\n rm -rf