How do I write a script for moving just the 20 oldest files from one folder to another? Is there a way to grab the oldest files in a folder?
|
It's easiest in zsh, where you can use the
Add the If you don't have zsh, here's a Perl one-liner (you can do it in less than 80 characters, but at a further expense in clarity):
With only POSIX tools or even bash or ksh, sorting files by date is a pain. You can do it easily with
|
|||
|
|
|
Parsing the output of Instead, use
What is all this doing?First, the
The timestamp is important. The The space is merely an arbitrary delimiter. The full path to the file is so that we can refer to it later, and the NULL character is a terminator because it is an illegal character in a file name and thus lets us know for sure that we reached the end of the path to the file. I have included The result of the
Since seconds-since-1970 always goes up we want the file whose timestamp was the smallest number. The first result from The results of the In the context of The first chunk of data, that represents the oldest file path preceded by its timestamp and a space, is read into the variable At this point the file name is stored in Isn't there a simpler way?No. Simpler ways are buggy. If you use Perhaps in specific cases you know for sure that a simpler way is sufficient, but you should never write assumptions like that in to scripts if you can avoid doing so. Solution
Call like:
To move the oldest 20 files from Note that I am including files and directories. For files only add ThanksThanks to enzotib and Павел Танков for improvements to this answer. |
|||||||||||
|
|
Combine Simple example, which works only if all file names contain only printable characters other than whitespace and
|
|||||||||||||||||||
|
|
You can use GNU find for this:
Where find prints the modification time (in seconds from 1970) and the name of each file of the current directory, the output is sorted according to the first field, the 20 oldest are filtered and moved to |
|||
|
|
|
No one has (yet) posted a bash example which caters for embedded newline chars (embedded anything) in the the filename, so here's one. It moves the 3 oldest (mdate) regular files
This is the test-data snippet
Here is the check-results snippet
|
||||
|
|
It's easiest to do with GNU Here is the syntax:
Remember that You can even combine
You can always get more information about
|
||||
|
|

atime(last access),ctime(last permission change), andmtime(last modified)... eg.ls -tand find'sprintf "%T"usemtime... It seems, according to this link, that myext4partitions are capable of handling a creation date, butlsandfindandstatdon't have the appropriate options (yet)... – Peter.O Oct 22 '11 at 10:14