Shell Script to Change Extension of Multiple Files in Unix

Filed Under: UNIX/Linux

In the Unix environment, mv is the command to move files and we can use it to change file extension also. But it works with a single file only and it doesn’t take wild characters also.

Shell Script to Change Extension of Multiple Files

Here I am providing a simple script that you can use to change the extension of multiple files in a directory.


#Save the file as


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

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

Below is the sample output from the above program execution.

$ ls
abc.txt		hi.doc		journaldev.doc
$ ./ doc txt
Changing Extension "hi.doc" --> "hi.txt" .
Changing Extension "journaldev.doc" --> "journaldev.txt" .
$ ls
abc.txt		hi.txt		journaldev.txt
$ ./ 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

change multiple files extension in a folder in unix shell script program

Assumptions for Script Execution

  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 file names having spaces but I can’t guarantee that it will work for you too.

I am feeling lazy to change the script to look into nested directories. If you can, do it and post in the comment section. 🙂

Leave a Reply

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

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