Mar 19 2008
Mass Rename File Extensions
I recently had to rename somewhere in the neighborhood of 100+ files as I was moving code from one platform to another. Obviously, I was looking for a quick solution, and what follows is the shell (Bash) script that I used to do the job:
#!/bin/bash
#
# Rename filename extensions:
#
# Example: ./ren txt xml
#
# Script needs to be set as executable using:
# > chmod a+x ren
#
# There must be two command line parameters
# If not, display message and exit
if [ $# -ne 2 ]
then
echo Usage: $0 old_extension new_extension
echo Example: $0 txt xml
exit 1
fi
# How many file were renamed
filecount=0
# For each matching extension...
for filename in *.$1
do
# Move file Strip off part of filename matching 1st argument,
# then append 2nd argument.
mv $filename ${filename%$1}$2
((filecount++))
done
echo Renamed $filecount files
exit 0
To use the script, save the code to a file (I used the name ren) and change the file type to executable as follows:
chmod a+x ren
With that, you can now change a group of file extensions in one fell swoop. For example, to change all files with the extension txt to xml:
./ren txt xml
A screenshot follows of the script in action.

The work horse behind all this is known as parameter expansion. You can learn more by following any of the links below:
Tips by RSS
Tips by Email
This doesn’t work if there are spaces in the file names, like in music
To work with spaces, put ” in line 28, so it will be:
mv “$filename” “${filename%$1}$2″
this is not worth a shell script — just type it in by hand
for i in *.txt; do mv $i `basename $i .txt`”.xml;done
of course, that doesn’t handle spaces right, so fix up the rest
for i in *.txt; do base=`basename “$i” .txt`; mv “$i” “$base”.xml;done
– peter
For some odd reason I had to change Peter’s second one to:
for i in *.mpeg; do mv “$i” “${i%mpeg}mod”;done
(I’m changing mpeg extensions back to mod so I convert them to dv files for Final Cut Pro X)
Oh, using Mac OSX Lion
By far the best, quickest ánd cheapest solution to change file extensions in batch on a Mac! Thanks!!
-Jan