如何通过Shell匹配带年月日的lb-quarzcenter.log.*并删除10天前日志
Delete Old Log Files by Filename Date
To remove lb-quarzcenter.log.* files where the filename includes a YYYY-MM-DD date that’s older than 10 days, we can’t rely on file modification times (since your log shows some files have mtimes later than their filename dates). Instead, we’ll parse the date directly from each filename and compare it to a cutoff date. Here’s a safe, step-by-step approach:
Step-by-Step Script (Test First, Delete Later)
Run this in your [root@amp logs]# directory. It will first list the files marked for deletion so you can verify before removing them:
#!/bin/bash # Calculate cutoff time: 10 days ago, converted to seconds since epoch cutoff=$(date -d "10 days ago" +%s) # Loop through all log files with date suffixes for file in lb-quarzcenter.log.*; do # Only process files with valid YYYY-MM-DD suffixes if [[ $file =~ lb-quarzcenter\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2} ]]; then # Extract the date string from the filename file_date_str=${file#lb-quarzcenter.log.} # Convert the filename date to seconds (skip invalid dates silently) file_date=$(date -d "$file_date_str" +%s 2>/dev/null) # If date is valid and older than cutoff, mark for deletion if [[ -n $file_date && $file_date -lt $cutoff ]]; then echo "Would delete: $file" # Uncomment the line below to actually delete the files # rm "$file" fi fi done
Key Notes:
- Safety First: Always run the script with just the
echoline first to confirm you’re targeting the right files. Only uncommentrm "$file"when you’re confident. - Date Validation: The regex ensures we skip the main
lb-quarzcenter.logfile and any incorrectly named files (like those with malformed dates). - Cross-Date Comparison: Converting dates to seconds since epoch makes it easy to numerically check if a file’s date is older than 10 days.
- Error Handling: Any filename with an invalid date (e.g.,
lb-quarzcenter.log.2019-02-30) will be skipped automatically.
Concise One-Liner (For Quick Testing)
If you prefer a shorter version (still with safety check):
cutoff=$(date -d "10 days ago" +%s); for f in lb-quarzcenter.log.*; do [[ $f =~ \.[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] && d=${f#*.log.} && date -d "$d" +%s >/dev/null 2>&1 && (( $(date -d "$d" +%s) < cutoff )) && echo "Would delete: $f"; done
Replace echo "Would delete: $f" with rm "$f" when ready to delete.
内容的提问来源于stack exchange,提问作者jiaqiang liu
相关产品推荐
相关产品推荐

