Issue
I have a directory that includes log files, that includes the following date format (YYYY-MM-DD) in the filename.
app-2020-12-17.log.2
app-2020-12-18.log.1
app-2020-12-18.log.2
app-2020-12-18.log.31
app-2020-12-18.log.32
app-2020-12-18.log.33
app-2020-12-18.log.3.gz
app-2020-12-20.log.4.gz
app-2020-12-20.log.5
My goal is to remove all files older than X date (using the date in the filename as comparison). For example, I want to remove all files older than 2020-12-20, so after the operation I should be left with the following files in my folder:
app-2020-12-20.log.4.gz
app-2020-12-20.log.5
How can I achieve this behavior? I have tried using somethine like this find app*log* -maxdepth 1 -mtime +1
, but this only finds files by modification date, and not the way I need.
Solution
With bash
and a regex:
for i in app-*.log*; do
[[ "$i" =~ -([0-9]{4}-[0-9]{2}-[0-9]{2}) ]] \
&& [[ "${BASH_REMATCH[1]}" < "2020-12-20" ]] \
&& echo rm -v "$i"
done
${BASH_REMATCH[1]}
contains 2020-12-17
, e.g.
As one line:
for i in app-*.log*; do [[ "$i" =~ -([0-9]{4}-[0-9]{2}-[0-9]{2}) ]] && [[ "${BASH_REMATCH[1]}" < "2020-12-20" ]] && echo rm -v "$i"; done
Output:
rm -v app-2020-12-17.log.2 rm -v app-2020-12-18.log.1 rm -v app-2020-12-18.log.2 rm -v app-2020-12-18.log.31 rm -v app-2020-12-18.log.32 rm -v app-2020-12-18.log.33 rm -v app-2020-12-18.log.3.gz
Answered By - Cyrus Answer Checked By - Cary Denson (WPSolving Admin)