Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question

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

share|improve this answer
Assuming the file names only contain printable characters other than newlines. Doing this in the general case with only POSIX features is difficult. – Gilles Jun 1 '12 at 23:06
Which is why they're talking about banning control characters in filenames. – Joshua Dec 18 '15 at 16:12

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.

share|improve this answer
yep stat was useful until this POSIX constarint came along. – Sandeep Jun 4 '12 at 6:39

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.