Skip to content

Instantly share code, notes, and snippets.

@cosmoscalibur
Created June 24, 2019 00:53
Show Gist options
  • Save cosmoscalibur/2f2280a66a538425a5e0f4a828bf1b5c to your computer and use it in GitHub Desktop.
Save cosmoscalibur/2f2280a66a538425a5e0f4a828bf1b5c to your computer and use it in GitHub Desktop.
Bash script to normalize filenames (lower case and underlines instead of spaces)
#! /usr/bin/env bash
SAVEIFS=$IFS
IFS=$'\n'
FILES=$(find . -iname "$1")
for FILE in ${FILES[@]}; do
DIRECTORY=$(echo $FILE | sed -n -E 's/^(\.?\/?(.+\/))?(([^\/]+)(\.([^\.\/]+))?)$/\1/p')
FILENAME=$(echo $FILE | sed -n -E 's/^(\.?\/?(.+\/))?(([^\/]+)(\.([^\.\/]+))?)$/\3/p')
FILENAME_NORM=$(echo $FILENAME | sed -E -e 's/./\l\0/g' -e 's/( |_)+/_/g' \
-e 's/^_//' -e 's/(_|-)\./\./g' -e 's/\.\./\._/g')
if ! [[ "$DIRECTORY$FILENAME" = "$DIRECTORY$FILENAME_NORM" ]]; then
if [[ -e "$DIRECTORY$FILENAME_NORM" ]]; then
rm $DIRECTORY$FILENAME
else
mv $DIRECTORY$FILENAME $DIRECTORY$FILENAME_NORM
fi
fi
done
IFS=$SAVEIFS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment