Mar 19 2008

Mass Rename File Extensions

Published by john at 7:02 am under System, Tools/Utilities

  
  

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.

Rename

The work horse behind all this is known as parameter expansion. You can learn more by following any of the links below:

Technorati Tags: ,

Trackback URI | Comments RSS

Leave a Reply