脚本如何按条件删除旧文件

wen 实用脚本 27

本文目录导读:

脚本如何按条件删除旧文件

  1. Linux/macOS Shell 脚本
  2. Python 脚本(跨平台)
  3. Windows PowerShell
  4. Windows 批处理 (.bat)
  5. 通用删除脚本(带配置)
  6. 安全建议
  7. 使用要点

Linux/macOS Shell 脚本

按文件年龄删除

#!/bin/bash
# 删除7天前的文件
find /path/to/directory -type f -mtime +7 -delete
# 或先预览再删除
find /path/to/directory -type f -mtime +7 -exec rm {} \;

按修改时间删除

#!/bin/bash
# 删除120分钟前的文件
find /path/to/directory -type f -mmin +120 -delete
# 删除访问时间超过30天的文件
find /path/to/directory -type f -atime +30 -delete

组合条件

#!/bin/bash
# 删除7天前、大于10MB的日志文件
find /var/log -type f -name "*.log" -mtime +7 -size +10M -delete
# 排除某些目录
find /data -type f -mtime +30 -not -path "/data/important/*" -delete

Python 脚本(跨平台)

#!/usr/bin/env python3
import os
import time
from pathlib import Path
def delete_old_files(directory, days=30, extensions=None):
    """
    删除指定天数前的文件
    """
    cutoff_time = time.time() - (days * 86400)  # 86400秒=1天
    for file_path in Path(directory).rglob('*'):  # 递归遍历
        if file_path.is_file():
            # 检查文件扩展名
            if extensions and file_path.suffix not in extensions:
                continue
            # 检查文件修改时间
            if file_path.stat().st_mtime < cutoff_time:
                print(f"删除: {file_path}")
                file_path.unlink()
# 使用示例
delete_old_files('/path/to/logs', days=7, extensions=['.log', '.tmp'])

Windows PowerShell

# 删除30天前的文件
$targetDir = "C:\Logs"
$daysOld = 30
$cutoffDate = (Get-Date).AddDays(-$daysOld)
Get-ChildItem -Path $targetDir -File | 
    Where-Object { $_.LastWriteTime -lt $cutoffDate } | 
    Remove-Item -Force
# 按条件组合
Get-ChildItem -Path $targetDir -File |
    Where-Object { 
        $_.LastWriteTime -lt $cutoffDate -and 
        $_.Length -gt 10MB -and 
        $_.Extension -in ".log", ".tmp"
    } | Remove-Item -Force -WhatIf  # -WhatIf 预览,去掉后实际删除

Windows 批处理 (.bat)

@echo off
setlocal enabledelayedexpansion
set "targetDir=C:\Logs"
set "daysOld=30"
forfiles -p "%targetDir%" -s -m *.* -d -%daysOld% -c "cmd /c del @path" 2>nul
echo 删除完成!
pause

通用删除脚本(带配置)

#!/bin/bash
# 配置区域
TARGET_DIR="/data/backup"
DAYS_OLD=7
FILE_PATTERN="*.tar.gz"
EXCLUDE_DIRS=("important" "current")
DRY_RUN=true  # true=预览, false=实际删除
# 构建排除参数
EXCLUDE_ARGS=""
for dir in "${EXCLUDE_DIRS[@]}"; do
    EXCLUDE_ARGS="$EXCLUDE_ARGS -not -path \"$TARGET_DIR/$dir/*\""
done
# 执行删除
if [ "$DRY_RUN" = true ]; then
    echo "【预览模式】将要删除的文件:"
    eval find "$TARGET_DIR" -type f -name "$FILE_PATTERN" -mtime +$DAYS_OLD $EXCLUDE_ARGS
else
    eval find "$TARGET_DIR" -type f -name "$FILE_PATTERN" -mtime +$DAYS_OLD $EXCLUDE_ARGS -delete
    echo "删除完成!"
fi

安全建议

添加日志功能

#!/bin/bash
LOG_FILE="/var/log/cleanup.log"
delete_with_log() {
    echo "$(date): 删除文件 $1" >> "$LOG_FILE"
    rm "$1"
}
# 使用
find /path -type f -mtime +30 | while read file; do
    delete_with_log "$file"
done

备份到回收站

#!/bin/bash
# 先将文件移动到回收站再删除
TRASH_DIR="/tmp/trash_$(date +%Y%m%d)"
mkdir -p "$TRASH_DIR"
find /path -type f -mtime +30 -exec mv {} "$TRASH_DIR" \;
# 确认无误后再删除回收站
echo "文件已移动到 $TRASH_DIR,请确认后手动删除"

使用要点

  1. 先测试:在生产环境前先用 -delete 换成 -print 预览
  2. 权限控制:确保脚本有适当权限
  3. 异常处理:检查磁盘空间、文件锁定等情况
  4. 定时执行:配合 cron (Linux) 或 任务计划程序 (Windows)

选择哪种方法取决于你的操作系统和具体需求,需要我帮你定制某个特定场景的脚本吗?

抱歉,评论功能暂时关闭!