Search code examples
rm

How to delete files older than a certain date in file name in Ubuntu


I have files in a single folder with the following naming convention: bkup_yyyymmdd.log

So there are, for example, the following files listed in reverse name order in the folder:

bkup_20210513.log

bkup_20210512.log

bkup_20210511.log

bkup_20210510.log

bkup_20210509.log

I'd like to delete files including and older than bkup_20210510.log. I have looked at this question, and whilst it seems very similar, there appears to be some 'argument' amongst those answering and I'm completely lost as to which answer is correct. Hence my re-posting here.


Solution

  • I used the following based on the answer to this question :

    weekago=`date -d -1week +%Y%m%d` 
    
    OLDERTHAN='./bkup_'$weekago'.log' 
    
    for fname in ./bkup_*.log; do test "$fname" "<" "$OLDERTHAN" && rm
     "$fname"; done
    

    Works a treat.