Delete all files older than 30 days, based on file name as date

前端 未结 3 360
[愿得一人]
[愿得一人] 2020-12-11 23:10

I\'m new to bash, I have a task to delete all files older than 30 days, I can figure this out based on the files name Y_M_D.ext 2019_04_30.txt.

3条回答
  •  时光取名叫无心
    2020-12-11 23:37

    I am by no means a systems administrator, but you could consider a simple shell script along the lines of:

    # Generate the date in the proper format
    discriminant=$(date -d "30 days ago" "+%Y_%m_%d")
    
    # Find files based on the filename pattern and test against the date.
    find . -type f -maxdepth 1 -name "*_*_*.txt" -printf "%P\n" |
    while IFS= read -r FILE; do
        if [ "${discriminant}" ">" "${FILE%.*}" ]; then
            echo "${FILE}";
        fi
    done
    

    Note that this is will probably be considered a "layman" solution by a professional. Maybe this is handled better by awk, which I am unfortunately not accustomed to using.

提交回复
热议问题