3

Is there a shell command to find the newest created files recursively from a root directory?

4 Answers 4

10
find /mydir -type f -exec stat -c '%y %N' {} \; | sort -n
2
  • 1
    You may want to tweak "%y". Refer to "man stat". Sep 3, 2009 at 20:08
  • 1
    In general, you should avoid using -exec for security reasons. GNU find offers -execdir as an alternative.
    – geocar
    Sep 3, 2009 at 20:50
6

This method uses only find (and sort):

find /somedir -type f -printf "%T+ %p\n" | sort

You can constrain it to the most recent 3 days, for example, like this:

find . -type f -mtime -3 -printf "%T+ %p\n" | sort

Or the last 42.5 hours:

find . -type f -mmin -2550 -printf "%T+ %p\n" | sort

which is the same as:

find . -type f -mmin -$((42 * 60 + 30)) -printf "%T+ %p\n" | sort
2

To avoid forking one process per file checked, if you're on a machine with GNU versions of find and xargs, consider something like this:

find /dir -type f -print0 | xargs -0 stat -c '%Y %N' | sort -n
1
  • with no time limit on find, it would match a lot more files.
    – Pieter
    Oct 26, 2016 at 2:02
0

This handles spaces correctly and executes a command (ls in this case) on a per file basis. Change (or delete) -n1 to execute the command on multiple files simultaneously.

find . -type f -printf "%T@ %p\0" | sort -z -nr | cut -z -d' ' -f2- |xargs -0 -n1 ls

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .