More fun, let's see if this works:
$ cat organize_files.sh #!/bin/bash sort_assoc_array() { for yr in ${years[@]} do echo $yr done|sort -n } declare -A years declare -a yrs file # collect files in top level directory to move files=( $(find . -maxdepth 1 -type f -name '20[01][0-9]*') ) # work out which year folders are needed for filex in ${files[@]} do dirx=${filex:2:4} [ ! -z ${years[$dirx]} ] || { echo add year $dirx years[$dirx]=$dirx } done # sort the years yrs=( $(sort_assoc_array) ) # create the year folders for yr in ${yrs[@]} do [ -d "$yr" ] || mkdir "$yr/" chown andrewm:andrewm "$yr/" done # move the files to their /year/ folder for filex in ${files[@]} do dirx=${filex:2:4} mv "$filex" "$dirx/" done # touch the year folder with the timestamp of the newest file for that year for yr in ${yrs[@]} do lastfileforyear=$(ls -rt ${yr}/|tail -1) touch -r "$yr/$lastfileforyear" "$yr/" done