Last active
August 1, 2024 10:58
-
-
Save bmunslow/a5b269cff7d66e1e58265dce584de5a1 to your computer and use it in GitHub Desktop.
Bash script to sanitize and transliterate filenames in Automator workflow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# activate extended pattern matching | |
shopt -s extglob | |
for f in "$@"; do | |
filename="$(basename "$f")" | |
dirpath="$(dirname "$f")" | |
# Get file extension | |
ext="${filename##*.}" | |
if ([ "$ext" == "$filename" ]) then | |
ext="" | |
else | |
# Prepend dot | |
ext=".${ext}" | |
fi | |
# Get file name without extension | |
filename="${filename%.*}" | |
# Transliterate all characters | |
filename=$(echo $filename | iconv -cs -f UTF-8 -t ASCII//TRANSLIT) | |
# Replace spaces with dashes | |
filename="${filename//+([[:space:]_.])/-}" | |
# Remove non-alphanumeric characters except dashes | |
filename="${filename//[![:alnum:]-]/}" | |
# Append extension | |
filename="$filename$ext" | |
# Rename file | |
mv "$f" "$dirpath/$filename" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment