Find the directories containing the most files

I needed to find the directories containing the most files, so I whipped up this bit of voodoo at the command line:

find . -type f -print | perl -na -F/ -e 'while (pop @F && @F) { print join ("/", @F)."n"; }' | sort | uniq -c | sort -n

This will count the number of files in each directory beneath your current directory, and print out those directories in ascending order by the number of files they contain. It will also print totals for parent directories–if “foo/bar” has one file, “foo/baz” has two, and “foo/” itself has one, then the line for “foo” will be printed with the number four.

Handy for me, possibly handy for you as well. This works in Linux and Mac OS X Leopard.

Advertisements

4 thoughts on “Find the directories containing the most files

  1. Would something along these lines this do what you wanted?

    for d in */; do set — “$d”*; printf “%s: %dn” “${d%/}” “$#”; done

    I don’t like needing perl in there… πŸ™‚

  2. I know what you mean–I didn’t want to have Perl in there, either. I initially tried to hook something up using only find, xargs, and wc, but couldn’t get the pipes to work out how I wanted them.

    I tried something like this:
    find . -type d -print0 | xargs -0 -I {} find {} -print | wc -l

    …but I needed the second pipe to apply to the second find, not to xargs. I couldn’t seem to hook that up.

  3. Oh, and the one you supplied only goes down one level, I think–it doesn’t recurse. πŸ™‚

  4. One more, with sorted output:

    find . -xdev -type d | while read a; do echo “`ls “$a” | wc -l` $a”; done | sort -nk1 | tail

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s