利用shell脚本或者php移动某个文件夹下的文件到各自的日期组成的目录下

  背景是这样的:网站一开始访问量比较小,大家就把所有的图片文件上传到一个目录下(比如是/data/images/)。后来访问量大了,图片也多了,这样就影响读取效率。所以有个这样的需求,把这些个图片文件移动到多个目录下,这个目录是图片的上传日期(就是文件属性中的修改日期filemtime)组成的。比如2012-12-20的修改日期,那么现在就该放在/data/images/2012/12/20的目录下。

  php有很容易的操作文件的函数,可以方便完成。当然也可以利用shell脚本完成。

  程序思路:遍历这个文件夹/data/images,查出每个文件的修改日期,然后建立这个日期的文件夹,再把该文件移动到日期文件夹的下面。

  查询修改日期的命令,有个stat,如下:可以找到Modify的日期

  

  比如我要找到这个hehe.log的修改日期:2016-03-04   (取得第六行第二列)

# stat hehe.log | awk 'NR==6{print $2}'

  接下来,我再把这个日期搞成这种格式,2016/03/04。

  可以使用sed的替换命令;-F是分隔符;或在命令里写FS="-",但是必须要有BEGIN

#  stat hehe.log | awk 'NR==6{print $2}' | sed 's/-///g'
#  stat hehe.log | awk 'NR==6{print $2}' | awk -F - '{print $1"/"$2"/"$3}'
#  stat hehe.log | awk 'NR==6{print $2}' | awk 'BEGIN{FS="-"}{print $1"/"$2"/"$3}'

  

  得到这个日期了,shell脚本也就自然出来了:

#/bin/bash

for file in ./* 
do
if [[ -f $file ]]
   then str=$(stat $file | awk 'NR==6{print $2}' | sed 's/-///g')
        if [[ ! -d ${str} ]]
           then mkdir -p ${str}
        fi  
        mv $file $str  
fi
done

顺便说下shell脚本的注意几点:[[  ]]这个判断命令,左右要留有空格。if下写then。$()是取执行结果赋给了变量。${}是取得这个变量的值。比如第7行的$str可以写成${str}。

做测试的时候,想再把新目录下的文件取回来还原。可以执行:find递归找出文件夹下的文件,然后移动到原来的目录下,-i是一行一行执行

# find . -type f | xargs -i  mv {} .

下面利用php脚本实现:

 1 <?php
 2 
 3 function mvPic($dir) {
 4     $opendir = opendir($dir);
 5     while($file = readdir($opendir)) {
 6 
 7         if($file != '.' && $file != '..') {
 8 
 9             $date = date('Y/m/d', filemtime($file));// 取出文件修改日期,格式为2012/11/12
10             $fullpath = $dir. "/". $date;
11             if (!is_dir($fullpath)){
12                 mkdir($fullpath, 0777, true);// true必须设置
13             }
14             rename($dir."/".$file, $fullpath."/".$file);// 移动文件
15         }
16     }
17     closedir($opendir);
18 }
19 
20 $dir_name = "/data/images";
21 mvPic($dir_name);
原文地址:https://www.cnblogs.com/firstForEver/p/5241619.html