最近遇到这样一个小需求,linux服务器上某个目录下有几百万个文件,导致各种操作不便,急需转移历史文件(保留90天),同时对转移到的目录下新建日期文件夹,按文件创建来存放文件,想到了两种解决方案。
第一种直接按创建日期find,这样需检索整个目录,可能效果不佳,代码如下:
#! /bin/sh
fromDir=/testDir
toDir=/tmp
cd $fromDir
startDate=20180926
endDate=20181010
startSec=`date -d "$startDate" "+%s"`
endSec=`date -d "$endDate" "+%s"`
for((i=$startSec;i<=$endSec;i+=86400))
do
temp_date=`date -d "@$i" "+%Y%m%d"`
next_date=`date -d "${temp_date}+1days" '+%Y%m%d'`
if [ ! -d "${toDir}/${temp_date}/" ];then
mkdir -p ${toDir}/${temp_date}/
chmod 774 ${toDir}/${temp_date}/
fi
echo "current_day:${temp_date} '---' $next_date"
find ${fromDir} -newermt ${temp_date} ! -newermt ${next_date} |xargs -i cp {} ${toDir}/${temp_date}
done
第二种方案:
1.先ls加awk的方式查出文件夹下所有的文件名保存到一个文件
ls -lrt|awk '{print $9}'>>/tmp/filename.txt
2.逐行读取步骤1的文件,取文件的修改时间,在目标文件夹下新建日期命名的文件夹;复制逐行读取的文件到目标文件夹下的日期文件夹,同时保存copy成功的文件名到一个文件
#!/bash/bin
fromDir=/sourcedir
toDir=/tmp
fileName=/tmp/filename.txt
current=`date "+%Y-%m-%d %H:%M:%S"`
timeStamp="`date -d "$current" +%s`"
while read line
do
#echo ${line}
#dirname
modifyDate=`stat "${fromDir}/${line}"|awk '$1=="Modify:"{ print $2}'|awk -F "-" '{print $1""$2""$3}'`
#get modifyTime second
modifyDate1=`ls --full-time "${fromDir}/${line}"|awk '{print $6}'`
modifyTime=`ls --full-time "${fromDir}/${line}"|awk '{print $7}'|awk -F "." '{print $1}'`
modifyDateSecond=`date -d "$modifyDate1 $modifyTime" +%s`
#check modify time
if [ ${modifyDateSecond} -lt ${timeStamp} ]
then
echo ${modifyDateSecond}${timeStamp}
continue
fi
#mkdir
if [ ! -d "${toDir}/${modifyDate}/" ];then
mkdir -p ${toDir}/${modifyDate}/
chmod 774 ${toDir}/${modifyDate}/
fi
#copy file
cp ${fromDir}/${line} ${toDir}/${modifyDate}/
#copy Success file
echo "${fromDir}/${line}" >> ${toDir}/copySuccess.txt
done < ${fileName}
3.逐行读取copy成功的文件,然后从源文件夹中删除,同时对文件创建时间进行判断,避免误删
#!/bash/bin
fileName=/tmp/copySuccess.txt
while read line
do
if [ ! -d "${line}" -a -z 'find ${line} -ctime +10' ];then
rm -f ${line}
fi
done < ${fileName}