Linux Rename Multiple Files Extension

Filed Under: UNIX/Linux

We can use mv command to change the file name. We can use it to change the file extension too. But, it works with a single file only and it doesn’t take wild characters.

We can create a shell script to change the extension of multiple files at once.

Linux Shell Script to Change Extension of Multiple Files

Let’s look at the script code where we will use the mv command in a for loop to change the extension of all the files in the current directory.

#!/bin/sh

#Save the file as multimove.sh

IFS=$'\n'

if [ -z "$1" ] || [ -z "$2" ]
then
  echo "Usage: multimove oldExtension newExtension"
  exit -1
fi
# Loop through all the files in the current directory
# having oldExtension and change it to newExtension
for oldFile in $(ls -1 *.${1})
do
# get the filename by stripping off the oldExtension
  filename=`basename "${oldFile}" .${1}`
# determine the new filename by adding the newExtension
# to the filename
  newFile="${filename}.${2}"
# tell the user what is happening
  echo "Changing Extension \"$oldFile\" --> \"$newFile\" ."
mv "$oldFile" "$newFile"
done

Usage: multimove.sh doc txt (to change all .doc to .txt)

Testing the Rename Shell Script

Below is the sample output from the above program execution.

$ ls
abc.txt		hi.doc		journaldev.doc	multimove.sh
$ ./multimove.sh doc txt
Changing Extension "hi.doc" --> "hi.txt" .
Changing Extension "journaldev.doc" --> "journaldev.txt" .
$ ls
abc.txt		hi.txt		journaldev.txt	multimove.sh
$ ./multimove.sh txt doc
Changing Extension "abc.txt" --> "abc.doc" .
Changing Extension "hi.txt" --> "hi.doc" .
Changing Extension "journaldev.txt" --> "journaldev.doc" .
$ ls
abc.doc		hi.doc		journaldev.doc	multimove.sh
$ 
Linux rename multiple files extension

Script Assumptions and Limitations

  1. The files have only one period (.)
  2. It loops through all files in the current directory only. However, you can extend it to look for files in the child directories also.
  3. Whitespaces in the file name can cause a problem with the script. It has worked on my system with filenames having spaces but I can’t guarantee that it will work for you too.

Further Readings: Linux mv command

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages