| 1 | #! /bin/bash |
| 2 | |
| 3 | input_dir="$1" |
| 4 | output_dir="$2" |
| 5 | |
| 6 | case "$output_dir" in |
| 7 | '') output_dir="$input_dir/auto-organized" |
| 8 | esac |
| 9 | |
| 10 | find "$input_dir" -type f -iregex '^.+\.jp[e]*g$' | while read -r path; do |
| 11 | # TODO Use "exiftool" instead of "file". Unclear which timestamp field to use. |
| 12 | file_data=$(file "$path") |
| 13 | if echo "$file_data" | grep 'image data' > /dev/null; then |
| 14 | read -r year0 month0 day0 hour0 minute0 second0 < <( |
| 15 | echo "$file_data" \ |
| 16 | | grep -o 'Exif Standard: \[.*\]' \ |
| 17 | | grep -oE 'datetime=[0-9]{4}:[0-9]{2}:[0-9]{2} +[0-9]{2}:[0-9]{2}:[0-9]{2}' \ |
| 18 | | sed 's/^datetime=//' \ |
| 19 | | sed 's/:/ /g' |
| 20 | ) |
| 21 | if ! [[ "$year0" = '' && "$month0" = '' && "$day0" = '' && \ |
| 22 | "$year0" -eq 0 && "$month0" -eq 0 && "$day0" -eq 0 ]] |
| 23 | then |
| 24 | # Force base 10, since leading zeros may cause an assumption of base 8: |
| 25 | year=$(( 10#${year0} )) |
| 26 | month=$(( 10#${month0} )) |
| 27 | day=$(( 10#${day0} )) |
| 28 | hour=$(( 10#${hour0} )) |
| 29 | minute=$((10#${minute0})) |
| 30 | second=$((10#${second0})) |
| 31 | |
| 32 | digest=$(sha256sum "$path" | awk '{print $1}') |
| 33 | suffix=$(echo "$path" | awk -F . '{print tolower($NF)}') |
| 34 | new_dir="${output_dir}/${year}/${month}/${day}" |
| 35 | new_name="${year}-${month}-${day}--${hour}-${minute}-${second}--${digest}.${suffix}" |
| 36 | new_path="$new_dir/$new_name" |
| 37 | |
| 38 | printf 'old: %s\n' "$path" |
| 39 | printf 'new: %s\n' "$new_path" |
| 40 | printf '\n' |
| 41 | fi |
| 42 | fi |
| 43 | done |