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

前端 未结 3 358
[愿得一人]
[愿得一人] 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.

    0 讨论(0)
  • 2020-12-11 23:41

    For delete file older than X days you can use this command and schedule it in /etc/crontab

    find /PATH/TO/LOG/* -mtime +10 | xargs -d '\n' rm

    or

    find /PATH/TO/LOG/* -type f -mtime +10 -exec rm -f {} \

    0 讨论(0)
  • 2020-12-11 23:57

    Here is another solution to delete log files older than 30 days:

    #!/bin/sh
    
    # A table that contains the path of directories to clean
    rep_log=("/etc/var/log" "/test/nginx/log")
    echo "Cleaning logs - $(date)."
    
    #loop for each path provided by rep_log 
    for element in "${rep_log[@]}"
    do
       #display the directory
        echo "$element";
        nb_log=$(find "$element" -type f -mtime +30 -name "*.log*"| wc -l)
        if [[ $nb_log != 0 ]] 
        then
                find "$element" -type f -mtime +30 -delete 
                echo "Successfull!"
        else
                echo "No log to clean !"
        fi
    done
    

    allows to include multiple directory where to delete files

    rep_log=("/etc/var/log" "/test/nginx/log")
    

    we fill the var: we'r doing a search (in the directory provided) for files which are older than 30 days and whose name contains at least .log. Then counts the number of files.

    nb_log=$(find "$element" -type f -mtime +30 -name "*.log*"| wc -l)
    

    we then check if there is a result other than 0 (posisitive), if yes we delete

    find "$element" -type f -mtime +30 -delete
    
    0 讨论(0)
提交回复
热议问题