44 lines
1.1 KiB
Bash
44 lines
1.1 KiB
Bash
#!/bin/bash
|
|||
|
|
|
||
|
|
# Change to your target directory
|
||
|
|
TARGET_DIR="./" # or set it via "$1" to pass folder as argument
|
||
|
|
|
||
|
|
if [[ "$1" != "" ]]; then
|
||
|
|
TARGET_DIR="$1"
|
||
|
|
|
||
|
|
fi
|
||
|
|
|
||
|
|
cd "$TARGET_DIR" || exit 1
|
||
|
|
|
||
|
|
for file in *.{jpg,jpeg,JPG,JPEG,png,PNG}; do
|
||
|
|
[ -f "$file" ] || continue # skip if not a file
|
||
|
|
|
||
|
|
# Extract DateTimeOriginal using exiftool
|
||
|
|
datetime=$(exiftool -DateTimeOriginal -s3 "$file")
|
||
|
|
|
||
|
|
if [[ -n "$datetime" ]]; then
|
||
|
|
# Format: "2023:08:21 14:32:10" -> "20230821_143210"
|
||
|
|
formatted=$(echo "$datetime" | sed 's/://g' | sed 's/ /_/g' | cut -c1-15)
|
||
|
|
echo $formatted
|
||
|
|
else
|
||
|
|
# Fall back to file modification time if no EXIF data
|
||
|
|
formatted=$(date -r "$file" +"%Y%m%d_%H%M%S")
|
||
|
|
fi
|
||
|
|
|
||
|
|
# Build new filename
|
||
|
|
extension="${file##*.}"
|
||
|
|
newname="IMG_${formatted}.${extension}"
|
||
|
|
|
||
|
|
# Avoid overwriting
|
||
|
|
if [[ -e "$newname" ]]; then
|
||
|
|
i=1
|
||
|
|
while [[ -e "IMG_${formatted}_$i.${extension}" ]]; do
|
||
|
|
((i++))
|
||
|
|
done
|
||
|
|
newname="IMG_${formatted}_$i.${extension}"
|
||
|
|
fi
|
||
|
|
|
||
|
|
echo "Renaming: '$file' -> '$newname'"
|
||
|
|
mv "$file" "$newname"
|
||
|
|
done
|
||
|
|
|