How to Find and Delete Files by Modified Date in Linux

I was given the task to delete all log files from year 2012 in a certain Linux directory. So today, I will be sharing with you how I did my task.

This can be achieved by using the find command. This command is very useful and has a lot of options to filter the results.

Below is the syntax we will be using:
# find /path -type f -maxdepth x -newermt "YYYY-MM-DD  HH:MM" ! -newermt "YYYY-MM-DD  HH:MM" -exec ls -lh {} \;

Note: Your user account should have access permissions on the target directory to execute the command (e.g. root). I also suggest you enable logging of your PuTTY or whatever terminal emulator you are using so you can view all the results in your query. This is useful specially when the scrollback buffer of your PuTTY session is limited.

# find /prod/files -type f -maxdepth 3 -newermt "2012-01-01 00:00" ! -newermt "2012-12-31 23:59" -exec ls -lh {} \;

maxdepth = how many subdirectories will be included in the search
newermt = compares the modified timestamp of the current file with reference
type = the type of file to search. in this case, f = regular file
exec = execute the command next to it. (in this case, we wanted to display the list first to verify before we actually delete it

After verifying the list of files displayed using the above command, we just need to replace ls -lh with rm -f to remove/delete the said files.

# find /prod/files -type f -maxdepth 3 -newermt "2012-01-01 00:00" ! -newermt "2012-12-31 23:59" -exec rm -f {} \;

For some older systems, the above command might not work because newert was stated to be an invalid predicate. To get around with this, we need to create a base file and set the modified date to the one we need.

To do this, we need to fire up below commands to create the files. Filenames and location may vary based on your liking.

# touch /tmp/mark.start -d "2012-01-01 00:00"
# touch /tmp/mark.end -d "2012-12-31 23:59"

And then rewrite the command using -newer predicate:

# find /path -type f -newer /tmp/mark.start ! -newer /tmp/mark.end -exec ls -lh {} \;
# find /path -type f -newer /tmp/mark.start ! -newer /tmp/mark.end -exec rm -f {} \;

That's it!

Do you know other commands to meet our requirements? Let's discuss it below.

No comments