简体   繁体   English

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

[英]Sort files to directories by date and filename

I got filenames that always start with YM (eg 2014-01) All files right now are in one directory, And I want to split them to a root year directory (2014) and sub-directories by month (01,02 etc..) 我得到的文件名总是以YM开头(例如2014-01),现在所有文件都在一个目录中,并且我想将它们拆分为根年目录(2014)和按月(01,02等)的子目录。 )

This is what I was doing so far manually: 到目前为止,这是我手动执行的操作:

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

And I would change the date and cp directory manually each time.. 而且我会每次手动更改日期和cp目录。

Can someone please help me with a bash script for it to happen automatically? 有人可以帮我提供一个bash脚本,以使其自动发生吗?

Thank you! 谢谢!

Try running: 尝试运行:

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;

Another solution: 另一个解决方案:

#!/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

ASSUMPTIONS: 假设:

  • The bash script is run from the path the files reside in bash脚本从文件所在的路径运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM