so I was wondering how I could do a simple find which would order the results by most recently modified. Here is the current fine I am using. (I am doing a shell escape in php, so that is the reasoning for the variables.

find '$dir' -name '$str'\* -print | head -10

How could I have this order the search by most recently modified. (Note I do not want it to sort 'after' the search, but rather find the results based on what was most recently modified)

Hopefully that makes sense. Thanks!

link|improve this question
feedback

migrated from stackoverflow.com Jun 7 '11 at 18:40

This question came from our site for professional and enthusiast programmers.

5 Answers

If you have GNU find, make it print the file modification times and sort by that. I assume there are no newlines in file names.

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

If you have Perl (again, assuming no newlines in file names):

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

If you have Python (again, 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]))[0: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).

link|improve this answer
feedback

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

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

find /wherever/your/files/hide -type f -exec ls -1rt "{}" +;
link|improve this answer
feedback

You do only need ls

You could do find /wherever/your/files/hide -type f -exec ls -1rt "{}" +; as stated above,

or

ls -1rt `find /wherever/your/file/hides -type f`
link|improve this answer
feedback

Try this very code find '$dir' -name '$str'\* -print | xargs ls -tl | head -10 but it's useful to filter data by -mmin/-mtime and -type

link|improve this answer
feedback

I don't think find has any options to modify the output ordering. -mtime and -mmin will let you restrict the results to files that have been modified within a certain time window, but the output won't be sorted -- you'll have to do that yourself. GNU find has a -printf option that, among other things, will let you print the modification time of each file found (format strings %t or %Tk) ; that might help you sort the find output the way you wish.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown