Classify files in a directory structure YYYY-MM-DD, with Script in Automator, getting it from their filenames

47 Views Asked by At

Having media (pictures and videos) without meta-data date, but are named with this date structure (YYYYMMDD_HHMMSS.jpg/ .mov/ .png...), I'm trying to classify them in folders named as their date, YYYY-MM-DD.

My bash version in Mac: GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin22) Copyright (C) 2007 Free Software Foundation, Inc.

My type -ap bash: bash is /bin/bash

I was trying this:

#!/usr/bin/env bash
dest_dir=/Users/myuser/photo-archive
for file in /Users/myuser/photo-archive/Blackhole/*.jpg; do
  [[ -f $file ]] || continue  # look at regular files only
  if [[ $file =~ ^([[:digit:]]{4})([[:digit:]]{2})([[:digit:]]{2}) ]]; then
    year=${BASH_REMATCH[1]}
    month=${BASH_REMATCH[2]}
    day=${BASH_REMATCH[3]}
    destination_dir=$dest_dir/$year-$month-$day
    mkdir -p "$destination_dir"
    echo "Moving $file to $destination_dir"
    mv "$file" "$destination_dir"
  fi
done

But I do not get anything.

Any idea where could be the error? I'm super lost.

Thanks

1

There are 1 best solutions below

6
oguz ismail On

You're forgetting that file contains the full path. The regex ^([[:digit:]]{4})([[:digit:]]{2})([[:digit:]]{2}) won't match a string starting with /Users/myuser/photo-archive/Blackhole/.

Change that conditional to this and it'll work.

[[ ${file##*/} =~ ^([[:digit:]]{4})([[:digit:]]{2})([[:digit:]]{2}) ]]