Unix/Linux find and sort by date modified

Use this:

find . -printf "%T@ %Tc %p\n" | sort -n

printf arguments from man find:

  • %Tk: File's last modification time in the format specified by k.

  • @: seconds since Jan. 1, 1970, 00:00 GMT, with fractional part.

  • c: locale's date and time (Sat Nov 04 12:02:33 EST 1989).

  • %p: File's name.


The easiest method is to use zsh, thanks to its glob qualifiers.

print -lr -- $dir/**/$str*(om[1,10])

If you have GNU find, make it print the file modification times and sort by that.

find -type f -printf '%T@ %p\0' |
sort -zk 1nr |
sed -z 's/^[^ ]* //' | tr '\0' '\n' | head -n 10

If you have GNU find but not other GNU utilities, use newlines as separators instead of nulls; you'll lose support for filenames containing newlines.

find -type f -printf '%T@ %p\n' |
sort -k 1nr |
sed 's/^[^ ]* //' | head -n 10

If you have Perl (here I'll assume there are no newlines in file names):

find . -type f -print |
perl -l -ne '
    $_{$_} = -M;  # store file age (mtime - now)
    END {
        $,="\n";
        @sorted = sort {$_{$a} <=> $_{$b}} keys %_;  # sort by increasing age
        print @sorted[0..9];
    }'

If you have Python (also assuming no newlines in file names):

find . -type f -print |
python -c 'import os, sys; times = {}
for f in sys.stdin.readlines(): f = f[0:-1]; times[f] = os.stat(f).st_mtime
for f in (sorted(times.iterkeys(), key=lambda f:times[f], reverse=True))[:10]: print f'

There's probably a way to do the same in PHP, but I don't know it.

If you want to work with only POSIX tools, it's rather more complicated; see How to list files sorted by modification date recursively (no stat command available!) (retatining the first 10 is the easy part).


You don't need to PHP or Python, just ls:

man ls:
-t     sort by modification time
-r,    reverse order while sorting (--reverse )
-1     list one file per line

find /wherever/your/files/hide -type f -exec ls -1rt "{}" +;

If command * exits with a failure status (ie Argument list too long), then you can iterate with find. Paraphrased from: The maximum length of arguments for a new process

  • find . -print0|xargs -0 command (optimizes speed, if find doesn't implement "-exec +" but knows "-print0")
  • find . -print|xargs command (if there's no white space in the arguments)

If the major part of the arguments consists of long, absolute or relative paths, then try to move your actions into the directory: cd /directory/with/long/path; command * And another quick fix may be to match fewer arguments: command [a-e]*; command [f-m]*; ...