Quote:
Originally Posted by SpLaSh212
I need to write something that deletes all the files in the directory except the files that were created within this week.
I'm not sure how I can do this, I mean, my plan is to take the date the script is executed in the date +%F format and divide it to $day,$month,$year
My question is how I can delete a file based on his date ?
Does anyone have any idea ?
|
For deleting files before or after an arbitrary date, your -newer solution is pretty close. One can (in Linux) create a
reference file using the
touch -t <date>. You then find files that are not newer using this:
Code:
touch -t 02190800
find dir/path \! -newer reffile -exec rm -f "{}" ";"
With bash, make sure you get the backslash \ or it will do strange things to you.
But if you want to delete all files within a specific number of ''days'', you can use find's
-mtime n feature, which will find files that were changed
n days ago. Preceeding
n with a + means before thist time, while preceeding it with a - will mean since that time. The GNU version accepts the parameter
daystart in case you want the days to count from the start of today.
Code:
find dir/path -mtime +7 -exec rm -f "{}" ";"
will remove files more than 7 days old.
Oh and
do be careful of using find and rm together!!