Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any trivial way to 'delete by date' using ´rm'- in bash?

Tags:

date

linux

bash

rm

I noticed today (after ~8 years of happily hacking away at bash) that there is no trivial way to 'delete by date' using ´rm'. The solution is therefore to pipe stuff around a combination of commands like rm, ls, find, awk and sed.

Say for example I wanted to delete every file in the working directory from 2009, what would be the typical approach?

I came up with the following, which is butt-ugly and should only be run if 'rm' is set to skip over directories (otherwise you will delete the parent directory):

ls -la | awk '{if (substr($6,0,5)==2009) print $8}' | xargs rm

Points for both the most elegant and the most outrageously over-engineered solutions.

like image 698
Fergie Avatar asked Jan 12 '09 09:01

Fergie


1 Answers

I would combine find and rm (without pipe)

find .  ...bunch of find criterias to select certain files (e.g. by date) .... -exec rm \{\} \;

EDIT: with parameters for your example it would be

find . -maxdepth 1 -type f -ctime -12 -exec rm \{\} \;

CAVEAT: This works just today :-). (To make it work everytime, replace the -ctime with absoulte time, see timeXY in the manpage )

like image 97
flolo Avatar answered Sep 17 '22 15:09

flolo