1. 用find方法
第一种find方式
#!/bin/bash
find /home/uftp/192.168.0.64/ -mtime +3 -delete -print | tee delete1.log | while read file; do echo "$(date) - Deleting $file" >> delete1.log; rm "$file"; done
find /home/uftp/192.168.0.65/ -mtime +3 -delete -print | tee delete2.log | while read file; do echo "$(date) - Deleting $file" >> delete2.log; rm "$file"; done
该方法可删除三天前所有的文件
- eg
要删除7天前的文件,你可以使用find
命令结合-mtime
参数来查找最后一次修改时间在7天前的文件,并使用-exec rm {} \;
参数来删除这些文件。下面是一个示例命令:
find . -name "test*" -mtime +7 -exec rm {} \;
这个命令会在当前目录(包括子目录)中查找文件名以 “test” 开头的文件,并且最后一次修改时间在7天前的文件,然后将这些文件删除。
比如
# .当前目录 替换路径即可
find /tmp/data -name "2024*" -mtime +7 -exec rm {} \;
第二种find方式
#! /bin/bash
historyDir=/home/slife/app/work/data/imgs
today=$(date +%Y-%m-%d)
echo "----------today is $today"
time=`date -d "-3 day" +%Y-%m-%d`
echo "next is to delete release before $time"
time2=`date -d $time +%s` #小于此数值的文件夹删掉
# 查找目录并删除旧的目录
find $historyDir -maxdepth 1 -type d -not -path "$historyDir" | while read -r dir
do
# 获取目录名,并转换成时间戳
dir_name=$(basename "$dir")
dir_time=$(date -d "$dir_name" +%s)
if [ "$dir_time" -lt "$time2" ]
then
echo "Deleting $dir_name ..."
rm -rf "$dir"
fi
done
该方法可删除三天前所有的文件
其他的find用法网上还有很多~~~
2. 普通rm -rf
#!/bin/bash
#需求:删除/home/efc/picture/ 下的文件内容
# 指定工作目录
work_dir=/home/efc/picture/
# 获取三天前的日期
tmp_date=`date -d"-3 day" +%Y-%m-%d`
# 拼接要删除的文件目录 ${work_dir}/${tmp_date} ====> /home/efc/picture/
rm -rf ${work_dir}/${tmp_date}
echo "${work_dir}/${tmp_date}"
# 输出一个日志
echo "已删除${tmp_date}文件夹下内容" >> app.log
echo "over"
该方法只能删除3天前的某一天,不可将历史的也删除
eg.删除一天前的日期文件夹
#!/bin/bash
y_day=`date +%Y%m%d --date='-3 day'`
base_path="/home/uftp/192.168.0.65/192.168.0.65"
echo "$base_path"
echo "$y_day"
img_path="$base_path*$y_day*.jpg"
echo $img_path
#sudo rm -rf $img_path
ls $img_path
针对上述的优化:
因为一天图片太多无法删除
使用Python 按小时删除
3. 用python的方式
import os
import datetime
def del_im(img_path_):
if os.path.exists(img_path_):
print(img_path_, "删除成功。")
os.remove(img_path_)
else:
pass
def handle_im(img, date):
if img.startswith(img_path.split("/")[-1]):
for i in range(24):
if len(str(i)) ==1:
img_p = img_path.split("/")[-1] + "_01_" + date + "0" + str(i) + img[26:]
img_path_ = os.path.join(img_path, img_p)
del_im(img_path_)
else:
img_p = img_path.split("/")[-1] + "_01_" + date + str(i) + img[26:]
img_path_ = os.path.join(img_path, img_p)
del_im(img_path_)
def del_date(day):
now = datetime.datetime.now()
print(now)
yes = now - datetime.timedelta(days=day)
yes_str = yes.strftime("%Y%m%d")
print('删除的日期时间为:', yes_str)
return yes_str
if __name__ == '__main__':
img_path = "/home/uftp/192.168.0.65"
img_sum = os.listdir(img_path)
# date = "20230826"
for day in range(1,6):
yes_str = del_date(day)
for img in img_sum:
handle_im(img, yes_str)
4. 参考
- https://www.cnblogs.com/zoulixiang/p/10574061.html
- https://blog.51cto.com/liangey/1719547