Skip to content

Instantly share code, notes, and snippets.

@s5csimmons
Created February 12, 2016 01:17
Show Gist options
  • Save s5csimmons/2bc1de7b9c50870d4dd5 to your computer and use it in GitHub Desktop.
Save s5csimmons/2bc1de7b9c50870d4dd5 to your computer and use it in GitHub Desktop.
#!/bin/bash
#Create a list of all of the songs that need converting
SONGS=$(find . \( -iname "*.m4a" -or -iname "*.webm" -or -iname "*.mp4" \) -maxdepth 1 | cut -c3-)
#If there are no songs to convert, alert user. Else, start looping through.
[[ -z $SONGS ]] && echo "Nothing here" || echo "$SONGS" | while read line
do
#We need to fix the original filename so that problem characters get escaped, has to be a better way.
fixed=$(echo $line | sed "s/ /\\\ /g; s/'/\\\'/g; s/,/\\\,/g; s/(/\\\(/g; s/)/\\\)/g; s/&/\\\&/g; s/\*/\\\*/g; s/\^/\\\^/g")
#We need to set up the new filename we want to use remembering to escape problem characters again.
mp3=$(echo ${line%-*.*}.mp3 | sed "s/ /\\\ /g; s/'/\\\'/g; s/,/\\\,/g; s/(/\\\(/g; s/)/\\\)/g; s/&/\\\&/g")
#Now we run the command. For some reason, just putting it here doesn't work. I tried in a sub-shell and with quotes
#in all sorts of places but it just won't work unless I do it this ghetto way.
echo "ffmpeg -i $fixed -q:a 0 $mp3" | bash
done
@s5csimmons
Copy link
Author

The whole point of this script is to find non-mp3 audio files and then convert them to mp3. Looping through files with spaces is miserable hence the reason I wrote the script.

For that last comment, I get a variety of errors. The current script work great but if I remove the echo and the pipe to bash:
1. If I put the bash first, it uses some weird PATH that can't see ffmpeg, which I'm sure I could fix easily.
2. If I quote the variables, ffmpeg sees the whole filename but fails saying it doesn't exist.
3. If I don't quote the variables, ffmpeg only sees the first "field" of the filename and fails.

That led me to the resolution you see above.

As for that ugly ass multiple sed, am I missing something that allows me to easily escape the problem characters?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment