5

I have been using the following script to organize my photos into "Date' Directories:

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

This script works great. My photo files follow the same naming convention 'IMG_20131125_090000.JPG' ie date and time photo taken. Is there a way to change the script above so that it categorizes into date directories still but using the date in the file name rather than use the date the file was modified?

3

Answer fixed to get 2013-11-25 instead of 20131125

If your script runs with a bash compatible shell, the easiest solution is to replace

d=$(date -r "$x" +%Y-%m-%d)

with

d="${x:4:4}-${x:8:2}-${x:10:2}"

portable solution with expr:

d=$(expr substr "$x" 5 4)-$(expr substr "$x" 9 2)-$(expr substr "$x" 11 2)

If you need only 20131125 instead of 2013-11-25 as directory name, you can also

Solution with sed:

d=$(echo "$x" | sed 's/.*_\([0-9]*\)_.*/\1/')

The sed commands replaces the filename with the number between the underscores (=the date).

Solution with awk:

d=$(echo "$x" | awk -F _ '{print $2}')

Solution with cut:

d=$(echo "$x" | cut -d_ -f 2')
  • All these solutions change the format of the date directory: you'll end up with a directory named 20131125 instead of 2013-11-25. – drewbenn Nov 25 '13 at 18:02
  • @drewbenn Thanks for point this out - I fixed the answer. – jofel Nov 25 '13 at 23:37
3

You can use :

export LC_ALL=C
for x in *.JPG; do
  d=$(date -d $( cut -d"_" -f2 <<< ${x} ) +%Y-%m-%d )
  mkdir -p "$d"
  mv -- "$x" "$d/"
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.