A script to remove spaces from filenames

Jun 11, '02 09:47:17AM

Contributed by: klieb2002

Perhaps you're like me, and have several years worth of JPEG files with names like "Aunt Sue's Birthday.jpg" These are a pain to deal with when putting together a web page, because most browsers don't handle spaces in file names well - you have to escape them with %20 or similar. I finally wrote a shell script that squeezes the spaces out of file names

Read the rest of the article for the script and a method for using it from the Finder instead of the Terminal...

The script:

#!/bin/sh
# this shell script removes the spaces out of the name of every file argument
# passed to it (handles an arbitrary number of files on the command line).
# example:
# sqzspaces.sh "/Users/Kurt/Name With Spaces"
# results in changing the filename to "/Users/Kurt/NameWithSpaces"

for OriginalFile
do

Location=`dirname "$OriginalFile"`
FileName=`basename "$OriginalFile"`

ShortName=`echo $FileName | sed 's/ //g'`

if [ $ShortName != "$FileName" ]
then
cd "$Location"
mv "$FileName" "$ShortName"
fi

done
[Editor's note: Copy and paste the text into a text editor, save the script, and then make it executable (chmod 755 sqzspaces.sh in the Terminal). To make it run from anywhere, make sure it's in a folder on your path -- I use ~/bin for my scripts, for example.]

The script assumes that the full pathname of the file is being given on the command line - which is what happens if you drag and drop a filename from Finder to the Terminal.

The real beauty of a script like this is that you can open it with ScriptGUI, a shareware application, and then Save As a scriptlet. Then all you have to do to perform this type of renaming is drag and drop the file(s) you want changed onto the scriptlet, and it will magically remove the spaces from the filenames. No need to open the Terminal!

Comments (12)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20020611094717930