Sorting files by date
My phone saves pictures with names in the format
IMG_YYYYMMDD_HHMMSS.jpg
I upload all images to my machine in a single directory, but I want to sort them by date. I use the following commands to sort them, in two phases :
First, create the directories
ls|cut -d_ -f2|sort -u|while read date; do mkdir -p /data/pictures/${date:0:4}/${date:0:4}-${date:4:2}-${date:6:2}; done
ls
gives all image namescut -d_ -f2
extracts the date of each picturesort -u
removes duplicate dates with the -u (unique) optionwhile read date
loops on all dates to run the next commandmkdir -p
creates the directory for the date, and eventually the year- The syntax
${date:0:4}
extract parts of the date. In this case the year
Then move images into directories
ls|cut -d_ -f2|sort -u|while read date; do mv *$date* /data/pictures/${date:0:4}/${date:0:4}-${date:4:2}-${date:6:2}; done
Only the command inside the loop is different :
mv *$date*
moves all pictures of the same day in the target directory
If the date is not in the file name, but is available in the directory, you can get it with the command ls --full-time
and parse the output, or you can use the command stat
to get exactly what you want, as it gives you full control on the output.