How can I copy the 5 newest files from a directory to another in a "new to old" order.
5 Answers
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
)
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
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
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.
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.