How to create a Bash script to change the extension of a set of files

How to create a Bash script to change the extension of a set of files

In this article, we will see how to create a Bash script that allows you to change the extension of a set of files, passing the new extension as a parameter.

Changing the extension of a set of files can be a common task, especially if you frequently work with text files, images, or documents that need to be converted to different formats. This process can be automated with a Bash script, making it efficient and fast. In this article, we will see how to create a Bash script that allows you to change the extension of a set of files, passing the new extension as a parameter.

At the beginning of the file, add the following line to indicate to the system that this script should be run with Bash:


#!/bin/bash

The script will accept two parameters: the old extension and the new extension. Add the following section to verify that the parameters have been provided:


if [ "$#" -ne 2 ]; then
  echo "Usage: $0 old_extension new_extension"
  exit 1
fi

This part of the code checks that the user has provided exactly two arguments. If not, the script displays a successful usage message and exits.

The parameters provided by the user will be stored in variables for ease of use:


old_extension=$1
new_extension=$2

Now, we can implement the logic to change the file extension. The script will search for all files with the old extension in the current directory and rename them with the new extension.


for file in *.$old_extension; do
  if [ -f "$file" ]; then
    base_name=$(basename "$file" .$old_extension)
    mv "$file" "$base_name.$new_extension"
    echo "Renamed $file as $base_name.$new_extension"
  fi
done

In this loop:

  • for file in *.$old_extension iterates through all files that match the old extension.
  • The base_name variable extracts the file name without the extension.
  • The mv command renames the file, replacing the old extension with the new one.
  • Finally, a message is printed confirming that each file has been renamed.

After saving the file, make it executable with the command:


chmod +x change_extension.sh

Now you can run the script directly from the terminal. Suppose you want to change the extension of all .txt files to .md. Run the command as follows:


./change_extension.sh txt md

This command will rename all files with the extension .txt in the current directory to .md.

Conclusion

This simple Bash script is a powerful tool for automating the process of changing file extensions. It can easily be extended or modified to include additional functionality, such as operating on subdirectories or filtering files based on additional criteria. Experimenting with Bash scripting allows you to improve your efficiency and solve common problems in an elegant and automated way.