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.

multimove.sh


#!/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)

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
$ 

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 *

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