Description
Do you need to clean your trace/log files using a specific criteria? There are simple Linux commands that can help you achiving this without having to do a complex script.
Here we will talk about the find command, which will help us to filter files with specific patterns and delete them.
Find command
The find command allow us to find files using specific patterns that matches our needs.
Notes:
- Before executing any command, please test it changing the “rm” option to for the “ls -l”. option. Below I will show an example of how to do this.
- You can combine all the below options and even more as required.
Examples
Scenario 1: Delete all files from specific dates
Test (-exec option will only list the files that match the given criteria):
find . -maxdepth 1 -newermt "2020-01-01 00:00:00" ! -newermt "2020-12-31 00:00:00" -exec ls -l {} \;
Real execution (-exec was changed to actually remove the files):
find . -maxdepth 1 -newermt "2020-01-01 00:00:00" ! -newermt "2020-12-31 00:00:00" -exec rm {} \;
Let’s break down the above command:
Argument/options | Details |
find | Command we are executing |
. | In this case the dot (.) means “here”. E.g. If we are in /root/, it would be the same replacing the dot (.) with /root/. |
– newerMT | The argument “newermt” allows you to compare the modification timestamp of the current file with the date and time you provide. |
! | Exclamation mark (!) in this case means “not”. E.g. If we wanted to find all files older than 2020, we could use ! -newermt “2020-01-01 00:00:00”, in this case we are saying all files not newer than 2020-01-01 00:00:00. |
-exec rm {} \; | This is the command that will actually do the delete. -exec: is for “executing” a command -rm {}: the curly brackets will be replaced with every file name that was returned by the file command |
Scenario 2: Delete all files ending in “.trc”
find . -iname "*.trc" -exec rm {} \;
In this case “-iname” will search for the files (case insensitive) ending in “.trc“. Remember that you can replace the -exec rm for -exec ls -l to list the files instead of removing them.
Scenario 3: Delete all files with the exception of the “.cnf” files
find . ! -iname "*.cnf" -exec rm {} \;
In this case the exclamation mark (!) means not, which basically we are saying “everything not ending in “.cnf“.
Regards.