I am looking for a single line shell script or unix command to find the newest 500 files in a directory. Major constraints are it should be POSIX complaint and the directory can have tons of files.

2 Answers 2


I'm pretty sure that you will need to stat every file in the directory in order to determine which are the 500 newest ones.

ls -t| head -n 500


If you mean files in the directory and all its subdirectories, something like

find . -exec sh -c \
    $'echo "$(stat -c "%Y" "$0")\t$0"' {} \; | \
    sort -k1nr | cut -f 2 | head -n 500

ought to do the trick.

Breaking it down:

  • find . -exec runs a command on every file below the current directory
  • sh -c "command" {} runs command for each file that find sees, with $0 set to the file name
  • stat -c "+%Y" "$0" prints the modification time of the file specified in "$0"
  • sort -k1nr sorts based on the first field in reverse numerical order
  • cut -f 2 strips out the modification time field, leaving only the file name
  • head -n 500 prints at most the top 500 lines

The $'...' and \t are because sort and cut use \t (i.e. TAB) as the field delimiter.

To be POSIX compliant, you can replace



"...<press Ctrl-V, Tab>..."

Unfortunately, stat isn't portable. Linux uses stat -c "%Y" but FreeBSD and Mac OS use stat -f "%m".

If you really want a portable method, it would be easier to use Python, Perl, or Ruby.

  • 1
    yep stat was useful until this POSIX constarint came along.
    – Sandeep
    Jun 4, 2012 at 6:39

You must log in to answer this question.

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