Skip to content

Instantly share code, notes, and snippets.

@onesixromcom
Created December 26, 2021 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onesixromcom/883186ff031d146744eb886b81b1a5d2 to your computer and use it in GitHub Desktop.
Save onesixromcom/883186ff031d146744eb886b81b1a5d2 to your computer and use it in GitHub Desktop.
Transliterate filenames in batch in shell
#!/bin/sh
# Rename utility.
if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
echo "usage: $(basename $0) FILE [...]"
echo
exit 0
fi
IFS=$'
'
for f in "$@"
do
if [ ! -f "$f" ]; then
echo "$(basename $0) warn: this is not a regular file (skipped): $f" >&2
continue
fi
NEWFILENAME="$(basename "$f")"
NEWFILENAME="$( echo -n "$NEWFILENAME" | { uconv -x 'Any-Latin;Latin-ASCII' || cat ; } )" # convert non-latin chars using uconv from the icu-devtools package
NEWFILENAME="$( echo -n "$NEWFILENAME" | iconv -f UTF-8 -t ascii//TRANSLIT//IGNORE )"
NEWFILENAME="$( echo -n "$NEWFILENAME" | sed -e 's/[+]/_plus_/g' \
|tr -c '[A-Za-z0-9._\-]' '_' \
| tr '\[\]' '_' \
| sed -e 's/__*/_/g' \
| sed -e 's/_\././g' )"
if [ -f "$(basename $f)/$NEWFILENAME" ]; then
echo "$(basename $0) warn: target filename already exists (skipped): $(basename $f)/$NEWFILENAME" >&2
continue
fi
if [ "$(basename $f)" != "$NEWFILENAME" ]; then
echo "\`$f' -> \`$NEWFILENAME'"
mv -i "$f" "$NEWFILENAME"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment