#!/bin/bash set -e _help() { self=$( readlink -f "$0" ) grep " # " "$self" | grep -v [\)] exit # jhead processor: renames images and videos with dates, and moves to subfolders # Give filenames as arguments e.x.: * # } which jhead &> /dev/null || { echo "jhead missing" exit 1 } function is_image() { jhead "$1" &>/dev/null } function gen_unique() { if [[ ! -e "$1" ]]; then echo "$1" return fi pathdir=$( dirname "$1" ) fullname="${1##*/}" extension="${fullname##*.}" filename="${fullname%.*}" aZ=( {a..z} {A..Z} ) idx=0 while true; do newname="${filename}.${aZ[$idx]}.${extension}" idx=$(( idx + 1 )) if [[ ! -e "$pathdir/$newname" ]]; then echo "$pathdir/$newname" return fi if [[ -z "${aZ[$idx]}" ]]; then echo "Cannot find unique filename for: $1" >&2 exit 1 fi done } function image() { newname=$( jhead -n%Y-%m-%d_%H%M%S "$1" ) if [[ -z "$newname" ]]; then newname="$1" else newname=${newname##*--> } fi if [[ ! -e "$newname" ]]; then echo Unexpected filename "$newname" >&2 exit 1 fi jhead -c -ft -autorot -cl "-" "$newname" move_to_dir "$newname" } function move_to_dir() { if [[ $DIRS -eq 0 ]]; then return fi pathdir=$( dirname "$1" ) fullname="${1##*/}" date=$( date '+%Y-%m-%d' -d "$( date '+%Y/%m/%d %H:%M:%S' -r "$1" ) + 4" ) mkdir -p "$pathdir/$date" tgt_name=$( gen_unique "$pathdir/$date/$fullname" ) mv -vi "$1" "$tgt_name" } function other() { pathdir=$( dirname "$1" ) fullname="${1##*/}" try_date=$( video_date "$1" ) [[ -n "$try_date" ]] && touch -d "$try_date" "$1" dname=$( date '+%Y-%m-%d_%H%M%S' -d "$( date '+%Y/%m/%d %H:%M:%S' -r "$1" )" ) tgt=$( gen_unique "$pathdir/${dname}.$fullname" ) mv -v "$1" "$tgt" move_to_dir "$tgt" } function video_date() { ffprobe -hide_banner "$1" 2>&1 | grep creation_time | \ head -n 1 | cut -d: -f2- | xargs -II date -d I 2>/dev/null } if [[ -z "$1" ]]; then _help fi DIRS=1 ONLYDIRS=0 for arg in "$@"; do case "$arg" in --nodir) # --nodir Do not move files to subfolders DIRS=0 ;; --onlydir) # --onlydir Move files to subfolders, but do not rename ONLYDIRS=1 DIRS=1 ;; --debug) # --debug turn on set -x set -x ;; --help) # --help This help message _help ;; -h) # This help message _help ;; esac done for file in "$@"; do if [[ "$file" = "-"* ]]; then continue fi if [[ -d "$file" ]]; then continue fi if [[ $ONLYDIRS -eq 1 ]]; then move_to_dir "$file" continue fi if is_image "$file"; then image "$file" else other "$file" fi done