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
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
-
4Assuming the file names only contain printable characters other than newlines. Doing this in the general case with only POSIX features is difficult. Jun 1, 2012 at 23:06
-
Which is why they're talking about banning control characters in filenames.– JoshuaDec 18, 2015 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 directorysh -c "command" {}
runscommand
for each file thatfind
sees, with$0
set to the file namestat -c "+%Y" "$0"
prints the modification time of the file specified in"$0"
sort -k1nr
sorts based on the first field in reverse numerical ordercut -f 2
strips out the modification time field, leaving only the file namehead -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.
-
1