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.

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

How can I copy the 5 newest files from a directory to another in a "new to old" order.

share|improve this question
There's a discrepancy between the subject and body of your question. Please clarify what you mean by "delete the old copies". Do you want to move those files? – Stéphane Chazelas Jan 22 '14 at 11:09

With zsh:

cp -- *(om[1,5]) /dest/dir


cp -- *(.om[1,5]) /dest/dir

To limit to regular files only.

With bash or ksh93 and GNU ls:

eval "sorted_files=($(ls -t --quoting-style=shell-always))"
cp -- "${sorted_files[@]:0:5}" /dest/dir

(note that those ignore hidden files. Add the D globbing qualifier, or the -A option to ls to include them).

To delete the 5 older ones, same in reverse order:

rm -- *(.Om[1,5])

(note the O instead of o). Or:

eval "sorted_files=($(ls -rt --quoting-style=shell-always))"
rm -- "${sorted_files[@]:0:5}"

(note the -r)

share|improve this answer

Assuming filenames don't contain newline characters:

set -f
for i in `ls -t /path/to/sourcedirectory | head -n 5`
  cp "/path/to/sourcedirectory/$i" /path/to/destdirectory/
share|improve this answer

On the assumption that the file names do not contain newlines in them:

ls -t | head -n5 | while IFS= read -r fname
    cp -- "$fname" newdir/

If, in addition, you want to delete the old copies, then use mv in place of cp:

ls -t | head -n5 | while IFS= read -r fname
    mv -- "$fname" newdir/
share|improve this answer

Well from the answers above, assuming the similar condition incase file names do not contain newlines in them:

ls -t | head -n5 | xargs -I{} mv {} $destination_dir

This would do.

share|improve this answer

Remove all files except the 5 newest ones:

find -type f -printf '%T@ %P\n' | sort -n | cut -d' ' -f2- | head -n -5 | xargs rm

You can easily adapt it to later copy/move files somewhere else.

Source: https://stackoverflow.com/questions/16190845/trying-to-delete-all-but-most-recent-2-files-in-sub-directories

share|improve this answer

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.