Mass Rename File Extensions

Wed, Mar 19

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:

# 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 ]
  echo Usage: $0 old_extension new_extension
  echo Example: $0 txt xml
  exit 1

# How many file were renamed

# For each matching extension...
for filename in *.$1
    # Move file Strip off part of filename matching 1st argument,
    # then append 2nd argument.
    mv $filename ${filename%$1}$2

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:


This doesn’t work if there are spaces in the file names, like in music

by Anonymous on May 18, 2008. #

To work with spaces, put ” in line 28, so it will be:

mv “$filename” “${filename%$1}$2″

by Everson Santos Araujo on May 22, 2008. #

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

by peter honeyman on Jun 9, 2008. #