Skip to content

Instantly share code, notes, and snippets.

@bmunslow
Last active August 1, 2024 10:58
Show Gist options
  • Save bmunslow/a5b269cff7d66e1e58265dce584de5a1 to your computer and use it in GitHub Desktop.
Save bmunslow/a5b269cff7d66e1e58265dce584de5a1 to your computer and use it in GitHub Desktop.
Bash script to sanitize and transliterate filenames in Automator workflow
#!/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