Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
644 views
in Technique[技术] by (71.8m points)

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

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.

I know I can list all files with ls in a the folder containing the files. I know I can get todays date with $ date and can configure that to match the file format $ date "+%Y_%m_%d"

I know I can delete files using rm.

How do I tie all this together into a bash script that deletes files older than 30 days from today?

In pseudo-python code I guess it would look like:

for file in folder:
    if file.name to date > 30 day from now:
        delete file
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
" |
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...