Skip to content

Instantly share code, notes, and snippets.

@dragonman225
Created November 19, 2019 16:55
Show Gist options
  • Save dragonman225/04a1e105276942e73be5e19969eb6330 to your computer and use it in GitHub Desktop.
Save dragonman225/04a1e105276942e73be5e19969eb6330 to your computer and use it in GitHub Desktop.
Rename music files with bad filenames (e.g. invalid encoding) with a "track description file" containing good filenames.
#!/bin/bash
# Usage:
# cat <file> | sh rename-tracks.sh
# Each line in <file> should be "<trackNo>.<trackName>"
# There must be an empty line at the end of file.
# Detect file extension.
if [ $(ls -1 *.mp3 2>/dev/null | wc -l) != 0 ]; then
fileExt="mp3"
elif [ $(ls -1 *.flac 2>/dev/null | wc -l) != 0 ]; then
fileExt="flac"
elif [ $(ls -1 *.wav 2>/dev/null | wc -l) != 0 ]; then
fileExt="wav"
else
fileExt="unknown"
fi
echo "Detected $fileExt"
# Rename files.
while IFS= read -r line
do
trackNo="$(echo "$line" | cut -d. -f 1 -s)"
trackName="$(echo "$line" | cut -d. -f 2- -s)"
# Skip invalid trackNo and trackName.
[ -z "$trackNo" ] && continue
[ -z "$trackName" ] && continue
mvSrc="$trackNo*"
mvDest="$trackNo.$trackName.$fileExt"
# Rename only when dest doesn't exist.
if [ ! -f "$mvDest" ]; then
echo "Rename $mvSrc to $mvDest"
mv $mvSrc "$mvDest"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment