Find directories in a given range size

120 Views Asked by At

I am trying to find directories in a given size but it doesn't display. I am running the code on the desired directory and I run

du -h --maxdepth 1

To make sure that the directories have the sizes I want to find. But when I run:

find . -maxdepth 1 -type d -size +5M -size -3M

it doesn't display anything.

3

There are 3 best solutions below

0
Paul Hodges On

You're supplying mutually exclusive requirements, so nothing can match.

Use an or.

find . -maxdepth 1 -type d \( -size +5M -o -size -3M \)

If that gets no hits, maybe none of the directories at -maxdepth 1 fit the conditions. Try removing that.

find . -type d \( -size +5M -o -size -3M \)

I think you're not going to find a lot of directories >5M, though. find isn't reporting the same data as du. It's a lot like the ls vs du questioned asked here.

maybe what you want is something more like one of these.

du -b | awk '$1<3000000||$1>5000000' # or
du -b | awk '$1<3145728||$1>5242880' | sort -n
0
Gilles Quénot On

What I would do to find dirs in range 3 to 5MiB:

find . -maxdepth 1 -type d -exec bash -c '
        for d; do
            s=$(du -s -B M "$d" | sed -E "s/^([0-9]+).*/\1/")
            ((s>=3 && s<=5)) && echo "$d ${s}MiB"
        done
    ' bash {} +

warning find's -size is meant for files, not for directory.


Or as far as you only treat only current directory:

du -sb */ | awk '$1>3000000 && $1<5000000'
0
Renaud Pacalet On

find -type d -size does not work as you apparently think. It considers the size of the directories that ls -l shows, not the total size of the content of the directories (the files they contain). If you are interested in the total size of the content you must use du in your find command:

find . -maxdepth 1 -type d -execdir bash -c \
  's=($(du -sb "$1")); (( 3145728 <= s[0] && s[0] <= 5242880 ))' _ {} \; -print

Note that -size +5M -size -3M means "strictly more than 5M and strictly less than 3M" which, even if the find directory sizes were what you think, would obviously return nothing. Note also that, due to the rounding, -size -3M means less or equal than 2M and -size +5M means more or equal 6M.