对linux目录下的文件按修改时间分别保存(按修改时间建文件夹,move到对应文件夹)

本文介绍了一种在Linux环境下,通过Shell脚本自动将大量文件按修改时间归档到相应文件夹的方法,有效提高了文件管理和检索效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

linux环境中多个文件夹下文件数量较大,有的文件夹下文件数量达到200万个,各种操作不便,需检索整个目录耗时较长,需按文件的修改时间在该文件夹下创建新的文件夹,然后把该文件mv过去,直接上代码

#!/bin/bash
umask22
transferDirs="/home/sully/move_test,/tmp"

#transfer day
dayCount=3
#控制日期
expirationDate=`date -d "3 days" +%s`

array=({transferDirs//,/ })
for transferDir in ${array[@]}
do
        #touch transfer log
        transferLog=${transferDir}/transfer_to_dir_success.log
        if [ ! -f "${transferLog}}" ]
        then
                touch ${transferLog}
                chmod 777 ${transferLog}
        fi

        cd ${transferDir}
        #当前时间
        startTime=`date +'%Y-%m-%d %H:%M:%S'`
        #打印开始时间
        echo "${startTime} start transfer Dir:${transferDir}" >>${transferLog}
        startSeconds=$(date --date="${startTime}" +%s);
        #查询需处理的文件
        transferFiles=`find ${transferDir} -maxdepth 1 -type f ! -name "*.log" -mtime +${dayCount}`
        #逐个文件处理
        for transferFile in ${transferFiles}
        do
                modifyDate=`stat "${transferFile}"|awk '$1=="Modify:"{print $2}'|awk -F "-" '{print $1""$2""$3}'`
                echo ${transferFile}    
                #get modifyTime second
                modifyDate1=`ls --full-time "${transferFile}"|awk '{print $6}'`
                modifyTime=`ls --full-time "${transferFile}"|awk '{print $7}'|awk -F "." '{print $1}'`
                modifyDateSecond=`date -d "${modifyDate1} ${modifyTime}" +%s`

                #check modify time
                if [ ${modifyDateSecond} -gt ${expirationDate} ]
                then
                        echo "${modifyDateSecond} 大于 ${expirationDate}"
                        continue
                fi

                #mkdir
                toDir=${transferDir}/${modifyDate}/
                if [ ! -d "${toDir}" ]
                then
                        mkdir -p ${toDir}
                        chmod 755 ${toDir}
                fi

                #copy file
                mv ${transferFile} ${transferDir}/${modifyDate}/
                echo "move ${transferFile} success" >> ${transferLog}
        done
        endTime=`date +'%Y-%m-%d %H:%M:%S'`
        endSeconds=$(date --date="${endTime}" +%s);
        echo "目录${transferDir}迁移到修改时间的文件夹,其运行时间:" $((endSeconds-startSeconds))"s">>${transferLog}
done

脚本的操作说明:

1.transferDirs里包含多个目录,用逗号隔开,新增处理目录比较方便;用逗号split,然后对单个目录处理

2.该脚本只处理三天前的文件,dayCount可随意配置

3.在查找transferFiles时,只搜索下一级目录,且过滤掉log文件,三天前的文件

4.通过stat,ls --full-time命令查看文件的修改时间

5.同时记录了迁移成功的文件和运行时间


脚本涉及知识点说明

字符串分割

shell 使用指定的分割符来分割字符串

#!/bin/bash
 
string="20181205,shell,split,test"  
array=(${string//,/ })  
 
for var in ${array[@]}
do
   echo $var
done 

find排除某类文件及往下一级目录

find /home/sully/test -maxdepth 1 -type f ! -name "*.log" 

-maxdepth 往下几级查找

-type f 查找类型为文件

! -name "*.log"排除log文件

批量移动文件通常需要编程脚本或者批处理命令来完成,尤其当文件列表存储在一个表格或者Excel文件中时。以下是一个简单的步骤示例: 1. **数据准备**: - 将文件名和目标文件夹路径整理成一个表格,每行包含一个文件名和对应文件夹路径。 - 确保文件名列的数据是完整的,并且目标文件夹确实存在。 2. **选择合适的语言或工具**: - 如果是在Windows系统,可以使用Python的`os`模块,如`shutil.move()`函数。 - 如果在Linux或MacOS,可以使用`shutil.move()`或者`cp`结合通配符操作。 - 使用批处理(`.bat`或`.cmd`)文件在Windows上也是可行的。 3. **编写脚本或创批处理**: - Python示例: ```python import os import pandas as pd # 加载文件夹名和文件名数据 data = pd.read_csv('file_list.csv') # 假设文件名为'file_list.csv' for index, row in data.iterrows(): src_file = row['File Name'] dst_dir = row['Target Folder'] dst_path = os.path.join(dst_dir, src_file) shutil.move(src_file, dst_path) # 移动文件 ``` - 批处理命令示例(假设文件列表保存在文本文件里,一行一个文件名): ```batch @echo off setlocal enabledelayedexpansion for /f "tokens=*" %%a in (file_list.txt) do ( move "%%a" "!TargetFolder!%%~na" ) ``` 其中`file_list.txt`是包含文件名的文件,`TargetFolder`是你设置的目标文件夹名。 4. **运行脚本或执行批处理**: - 对于Python脚本,直接运行即可。 - 对于批处理,双击运行或者通过命令提示符输入命令后回车。 5. **检查结果**: 检查移动后的文件是否都在正确的目录下,确认无误后,文件就成功批量移动了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值