Sort directories by the newest file

Published on

If you need to clean up a file system (especially your $HOME directory from some ancient dot-files), it may be useful to sort the top-level directories by the last modified time of any file inside them.

Here’s the command I came up with:

find -printf '%T@/%P\n' | awk -F/ \
  '{t[$2] = t[$2] > $1 ? t[$2] : $1}
   END {
     PROCINFO["sorted_in"] = "@val_num_asc";
     for (key in t) {
       printf "%s\t%s\n", strftime("%F", t[key]), key

And here’s how the output looks like:

2007-07-30      .gkrellm2
2007-08-04      .gobby
2007-08-17      .imgseek
2007-08-25      .kderc
2007-09-12      .ftp_banner
2007-09-18      .BitchX

Thank you to numerous StackOverflow users from whose questions and answers I benefited; in particular the ones about printing mtime from find and sorting an AWK array.