简体   繁体   中英

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..)

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..

Can someone please help me with a bash script for it to happen automatically?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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