按日期和文件名将文件排序到目录

时间:2015-06-07 12:57:53

标签: linux bash

我的文件名始终以Y-M开头(例如2014-01) 现在所有文件都在一个目录中, 我想将它们分成一个根年目录(2014)和按月目录的子目录(01,02等)。

这是我到目前为止手动做的事情:

   find /dirlocation/ -name "2014-12*" -type f -exec mv {} /pathtocp/2014/12 \;

我每次都会手动更改日期和cp目录..

有人可以帮我用bash脚本自动发生吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

尝试跑步:

for i in 2014 2015; do
  for j in `seq 1 12`; do
    j=`printf %.2d $j`          #to convert 1 to 01
    find /dirlocation/ -name "$i-$j*" -type f -exec mv{} /pathtocp/$i/$j \; #assuming this sentence is correctly written in question.
   done;
done;

答案 1 :(得分:1)

另一种解决方案:

#!/bin/bash
for f in $(find . -type f -regextype posix-extended -regex "./[0-9]{4}-[0-9]{2}.*"); do
    y=${f:2:4}
    m=${f:7:2}
    mkdir -p "$y/$m" && mv "$f" "$y/$m/$f"
done
  

假设:

     
      
  • bash脚本从文件所在的路径运行
  •   
相关问题