1

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

Sandeep
  • 67
  • 1
  • 6

5 Answers5

2

I found from the below link a perl script which helped:

find . -type f -print | perl -l -ne ' $_{$_} = -M; END {  $,="\n";   print sort {$_{$b} <=> $_{$a}} keys %_   }' | head -n 500

How to recursively find and list the latest modified files in a directory with subdirectories and times?

Any more comments most welcome.Thanks all.

Community
  • 1
  • 1
Sandeep
  • 67
  • 1
  • 6
1

How about this:

Posix ls and head

ls -tc DIR | head -n 500
Paul Rubel
  • 26,632
  • 7
  • 60
  • 80
  • 2
    `ls` is not entirely reliable, in that its output is not meant to be machine readable, so this should be avoided in the general case. If your file names are regularly formed, you could be getting along fine with this, but it could blow up on you one day. – tripleee Jun 01 '12 at 19:07
1

find . -type f -print | perl -l -ne ' ${$} = -M; END { $,="\n"; print sort {${$b} <=> ${$a}} keys %_ }' | head -n 500

It should be the contrary for the sort ${$a} <=> ${$b}

The head can be avoided: print+(...)[0..499]

The find too with a recursive call:

perl -e 'sub R{($_)=@_;map{-d$_?&R($_):$_}<$_/*>}print$_,$/for(sort{-M$a<=>-M$b}R".")[0..499]'

Or with an unix cmd: not sure if there are to many arguments may fail

find . -type f -exec ls -1t {} + | head -500
find . -type f -print0 | xargs -0 ls -1t | head -500
Nahuel Fouilleul
  • 18,726
  • 2
  • 31
  • 36
0
find . -type f -exec stat -c %Y:%n {} \; |
  sort -rn | sed -e 's/.*://' -e 500q

This sorts on ctime, which can be changed by using %Z or %X in the format string, but stat is not POSIX.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
0

There is no 100% reliable POSIX way of doing this with shell scripting.

A POSIX C program will do it easily though, assuming you define newest by either last modified file content or last changed file. If you mean last creation time, there is no POSIX way and possibly no solution at all, depending on the file system used.

jlliagre
  • 29,783
  • 6
  • 61
  • 72