I'm looking for a Bash script that will go into a list of directories and delete all but the four most recently created files.
How can I do this?
|
I'm looking for a Bash script that will go into a list of directories and delete all but the four most recently created files. How can I do this? |
|||||||
|
Remove the If you have filenames with spaces, more work is required. |
|||||||||
|
|
|
Do you want to keep the four most recent files in each directory, or the four most recent files in ANY directory? To solve the first problem, you would use find to list each directory, then in each, remove all but the four most recent files. This isn't too hard. To solve the second problem takes a bit more thought, but is actually easier to write. Basically, find every file recursively. Call the "stat" command returning the file's modification time and name. Sort this descending numerically, and skip the first four files, which are the most recent. Then remove the leading timestamps, and remove the resulting list of filenames. Something like (untested):
This should work, though you'll want to remove the 'echo' in the while loop to make it effective. Test it carefully first! |
|||||
|
|
I realise this isn't quite what you're asking, but for this kind of backup I prefer to rotate the log files before creating the new one. It's a bit more explicit, and much simpler to code, like this:
|
|||
|
|
|
This command should work
If you don't want the command to delete files recursively, add the option The command recursively prints each file with its last modification date ( |
|||
|
|
|
The most simplest method:
|
|||
|
|