Skip to content

Instantly share code, notes, and snippets.

@MoriTanosuke
Last active February 25, 2016 15:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save MoriTanosuke/3438761 to your computer and use it in GitHub Desktop.
Save MoriTanosuke/3438761 to your computer and use it in GitHub Desktop.
Fix broken filenames. Removes all non-alphanumeric characters from directory and filenames from a given directory and copies them into the current directory. I'm using this to help me organize and backup my music on multiple devices.
#!/bin/bash
#
# Sanitizes all files in the given path
# and makes them lowercase too.
#
# param 1: source directory
# param 2: target directory
shopt -s extglob;
# copy as default, you have to change this if you want to move files
MV=cp -v
#MV=mv -v
source="$1"
target="$2"
find ${source} -depth -type f -print | while read path
do
filename=$(basename "$path")
directory=$(dirname "$path")
# remove original path from target to avoid deep path in target directory
directory_clean=${directory#$source}
target="$(dirname "$target")/$(basename "$target")"
# remove invalid chars from directory/filename
directory_clean="${directory_clean//+([^[:alnum:]_-\.\/])/_}"
filename_clean="${filename//+([^[:alnum:]_-\.])/_}"
mkdir -vp "${target}/${directory_clean,,}"
${MV} "$directory/$filename" "${target}/${directory_clean,,}/${filename_clean,,}"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment