Monday, 23 July 2018

Quick script to organize files in directories by date

Quick script to organize files in directories by date
Let's say you have a bunch of files in a single directory you'd like to organize them in directories by date. Here's one way to do it using a shell script.
For example, create some files:
touch file0
touch -d "yesterday" file1
touch -d "2 days ago" file2
touch -d "2 days ago" file3
I now have four files in the current directory:
$ find -type f | xargs ls -l --time-style long-iso
-rw-rw-r-- 1 ak ak 0 2013-04-13 14:30 ./file0
-rw-rw-r-- 1 ak ak 0 2013-04-12 14:30 ./file1
-rw-rw-r-- 1 ak ak 0 2013-04-11 14:30 ./file2
-rw-rw-r-- 1 ak ak 0 2013-04-11 14:30 ./file3
Time to get organized!
OrganizeByDate
processing 2013-04-11..
creating dir 2013-04-11..
moving file2 to 2013-04-11/
moving file3 to 2013-04-11/
processing 2013-04-12..
creating dir 2013-04-12..
moving file1 to 2013-04-12/
processing 2013-04-13..
creating dir 2013-04-13..
moving file0 to 2013-04-13/
Now, each of the four files is in a directory named after its creation date:
find -type f | xargs ls -l --time-style long-iso
-rw-rw-r-- 1 ak ak 0 2013-04-11 14:30 ./2013-04-11/file2
-rw-rw-r-- 1 ak ak 0 2013-04-11 14:30 ./2013-04-11/file3
-rw-rw-r-- 1 ak ak 0 2013-04-12 14:30 ./2013-04-12/file1
-rw-rw-r-- 1 ak ak 0 2013-04-13 14:30 ./2013-04-13/file0
And here's the script:
OrganizeByDate()
{
  all=$(ls -l --time-style long-iso | awk '$1!~/^d/ {print $6"|"$8}')
  for date in $(echo "$all" | awk -F'|' '$1!="" {print$1}' | sort -u); do
    echo processing $date..
    if [ ! -d $date ]; then
      echo creating dir $date..
      mkdir $date
    fi
    echo "$all" | grep "^$date" | cut -d'|' -f2 |
    while read f; do
      echo moving $f to $date/
      mv $f $date/
    done
  done
}

0 comments:

Post a Comment