3

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

vikke
  • 41
  • 1
    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

5 Answers5

2

With zsh:

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

Or:

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)

1

Assuming filenames don't contain newline characters:

IFS='
'
set -f
for i in `ls -t /path/to/sourcedirectory | head -n 5`
do
  cp "/path/to/sourcedirectory/$i" /path/to/destdirectory/
done
Ankit
  • 439
1

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

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

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
do
    mv -- "$fname" newdir/
done
John1024
  • 74,655
1

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.

Sriram
  • 21
1

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

BlackPioter
  • 141
  • 4