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?
Parsing the output of
What is all this doing?
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.
To move the oldest 20 files from
Note that I am including files and directories. For files only add
It's easiest to do with GNU
Here is the syntax:
You can even combine
You can always get more information about
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
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
Simple example, which works only if all file names contain only printable characters other than whitespace and
It's easiest in zsh, where you can use 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