Is there a trivial way to "delete by date" using "rm" in bash?

I noticed today (after 8 years of happy hacking in bash) that there is no trivial way to "delete by date" using "rm". So the solution is to pass 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 since 2009, what would be the typical approach?

I came up with the following, which is inconvenient and should only be started if "rm" is configured to skip directories (otherwise you will delete the parent directory):

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

Points for the most elegant and most outrageously redesigned solutions.

+3
source share
5 answers

Some versions of find support the -delete option, which makes it even more efficient ...

find . -maxdepth 1 -type f -ctime -12 -delete;

Check your search page (this worked for the most recent Ubuntu releases for me)

+8
source

I would combine find and rm (no pipe)

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

EDIT: with parameters for your example, it will be

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

CAVEAT: This only works today :-). (To make it work every time, replace -ctime with absoulte time, see TimeXY in the man page)

+10
source

:

find . -maxdepth 1 -type f -newerct 'jan 1' -print0 \
    | xargs -0 rm

( -newermt, )

, 't' -newerXY cvs (. doco).

+3

find(1) , , ls(1).

EDIT: - - , find, -print0 ( xargs -0) .

find . -mtime +12 -print0 | xargs -0 rm -f
+1
source

Instead of parsing ls (1), which might break too easily, you should rely on stat (1):

stat -c '%z/%n' files_or_glob | grep '^date' | cut -d/ -f2- | xargs -d '\n' rm -i

eg.

$ stat -c '%z/%n' *| grep '^2008-12-16' | cut -d/ -f2- | xargs -d '\n' rm -i

Note. This does not properly handle filenames with inline newlines. However, they are rare in wil.d

+1
source

All Articles