Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
add comment

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

share|improve this answer
2  
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
add comment

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

$'...\t...'

with

"...<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
1  
yep stat was useful until this POSIX constarint came along. –  Sandeep Jun 4 '12 at 6:39
add comment

Your Answer

 
discard

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.