Create sub-directories and organize files by date

9,512

Solution 1

On Linux and Cygwin, you can use date -r to read out the modification date of a file.

for x in *.JPG; do
  d=$(date -r "$x" +%Y-%m-%d)
  mkdir -p "$d"
  mv -- "$x" "$d/"
done

(I use the unambiguous, standard and easily-sorted YYYY-MM-DD format for dates.)

Solution 2

This also checks if the object to be organized is a file or not. This is an important check, failing which a date's directory can itself get moved into another date. In effect this makes the answer more idempotent, allowing multiple runs.

dir="mention the directory path"
cd "$dir"

for x in *; do
    if [ -f "$x" ]; then
        d=$(date -r "$x" +%Y/%B/%d)
        mkdir -pv "$d"
        mv -v -- "$x" "$d/"
    fi
done
Share:
9,512

Related videos on Youtube

Richard Ahlquist
Author by

Richard Ahlquist

Updated on September 18, 2022

Comments

  • Richard Ahlquist
    Richard Ahlquist over 1 year

    I have some directories of files copied from my security camera that I would like to organize into sub-directories by file date. So for example;

    -rwxrwxrwx 0 root root 4935241 Jul 19  2012 DSCN1406.JPG
    -rwxrwxrwx 0 root root 4232069 Jul 19  2012 DSCN1407.JPG
    -rwxrwxrwx 0 root root 5015956 Jul 20  2012 DSCN1408.JPG
    -rwxrwxrwx 0 root root 5254877 Jul 21  2012 DSCN1409.JPG
    

    I would like a script that runs to see the files in that directory, then create the 3 needed directories named like;

    drwxrwxrwx 1 root root     0 Sep  2 16:49 07-19-2012
    drwxrwxrwx 1 root root     0 Sep  2 16:49 07-20-2012
    drwxrwxrwx 1 root root     0 Sep  2 16:49 07-21-2012
    

    And then move the files into the appropriate directories. Does anyone have any suggestions on a good scriptable way to accomplish this?

  • Richard Ahlquist
    Richard Ahlquist about 11 years
    Perfect Gilles once I drop cased the .jpg it worked beautifully. Thank you!
  • Alkeindem
    Alkeindem over 5 years
    A shorter date format, same as %Y-%m-%d: date +%F
  • Gilles 'SO- stop being evil'
    Gilles 'SO- stop being evil' over 3 years
    @Acumenus No it won't. The date directories don't match *.JPG.