Looping Through Files with Spaces and Special Characters in BASH

This is useful for batch processing of files with special characters such as space, ampersand (&), underscore, etc. The example below is to do mass conversion of mp4 files I downloaded from youtube into mp3 files.

Instead of giving the command directly, I prefer always to “echo” the command so I can see whether it’s giving the desired batch command or not. If all okay, then remove the echo.

$ find ./ -type f | sed 's/.mp4//' | sed 's/\.\///' | while read FILE;
echo ffmpeg -i \"$FILE.mp4\" -ab 192k \"$FILE.mp3\";

But the with the above script, somehow ffmpeg won’t accept the filenames – although I already put quote in both end. Strange enough, if I give the command directly for example:
$ ffmpeg -i "Some file (3_11)_.mp4"
It works.

Let’s just focus on getting the job done shall we? The easiest workaround is by redirecting the output of the script above into a file by putting
> batch.sh
in the end of the script (right after “done”). So the batch file will look like this:

ffmpeg -i "Chaka Khan _ I'm Every Woman _(360p_H.264-AAC).mp4" -ab 192k "Chaka Khan _ I'm Every Woman _(360p_H.264-AAC).mp3"
ffmpeg -i "David Foster _ Winter Games _(360p_H.264-AAC).mp4" -ab 192k "David Foster _ Winter Games _(360p_H.264-AAC).mp3"
ffmpeg -i "Earth, Wind & Fire (3_11) - Fantasy(360p_H.264-AAC).mp4" -ab 192k "Earth, Wind & Fire (3_11) - Fantasy(360p_H.264-AAC).mp3"
ffmpeg -i "Earth, Wind & Fire (4_11) - Sing a song(360p_H.264-AAC).mp4" -ab 192k "Earth, Wind & Fire (4_11) - Sing a song(360p_H.264-AAC).mp3"

Then make the file executable
$ chmod +x batch.sh
and run it
$ ./batch.sh

Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: