AddModifiedDateToFileName

Add the modified date to the front of images.

#!/usr/bin/env bash
set -euo pipefail

# Usage info: how to run the script and optional folder argument
usage() {
  echo "Usage: $0 [folder]"
  echo "If no folder is specified, uses the current directory."
}

# Get target directory from first argument, default to current directory
target_dir="${1:-.}"

# Check if the target directory exists and is a directory
if [[ ! -d "$target_dir" ]]; then
  echo "Error: '$target_dir' is not a directory."
  usage
  exit 1
fi

echo "Started AddModifiedDateToFileName"

# Function to process a single file:
# - Check if filename starts with a letter (A-Z or a-z)
# - Get last modification date in yyyy-mm-dd format (macOS stat)
# - Rename file by prepending the date and a hyphen
process_file() {
  local filepath="$1"
  local filename
  filename="$(basename -- "$filepath")"

  # Only process files whose names start with a letter to avoid double renaming
  if [[ "$filename" =~ ^[A-Za-z] ]]; then
    # Get modification date in yyyy-mm-dd format (macOS)
    mod_date=$(stat -f "%Sm" -t "%Y-%m-%d" "$filepath")

    # Construct the new filename with date prepended
    local new_name="${mod_date}-${filename}"

    # Build the full path for the renamed file
    local new_path="$(dirname "$filepath")/$new_name"

    # Rename the file, but do not overwrite if new file exists (-n)
    if mv -n -- "$filepath" "$new_path"; then
      echo "Renamed  [$new_name]"
    else
      echo "Failed to rename '$filename'"
    fi
  fi
}

# Use 'find' to locate image files (case-insensitive extensions) at maxdepth 1 (non-recursive)
# Then process each file found
find "$target_dir" -maxdepth 1 -type f \( \
  -iname "*.png" -o -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.gif" -o \
  -iname "*.bmp" -o -iname "*.tiff" -o -iname "*.webp" \
  \) -print0 |
while IFS= read -r -d '' file; do
  process_file "$file"
done

echo "Finished AddModifiedDateToFileName"

Last updated