how to rename file extensions of multiple files in a folder from command line in linux

You might have several files inside a folder with the same file extension that you want to rename or change the file extension of. For example, you might want to change the all .text extension to .txt or all .jpeg extensions to .jpg.

If you want to rename just a single file, then it is easy enough to use the mv command to do that. So, to rename the file mytextfile.text to mytextfile.txt, you could do

$ mv -v mytextfile.text mytextfile.txt

Unfortunately, it is not possible to use the mv command to rename multiple files simultaneously. There is a different command called rename which tackles this scenario. If you have the rename command installed on your machine, then this is a simple enough process.

$ rename .text .txt myfile*.text

The above example will rename all files that match the regular expression myfile*.text. The .text part of the filename will be changed to .txt. The rename command is not limited to renaming just file extensions, you can use it rename any part of the file name.

In this post, we will look at how we can rename file extensions in batch without using the rename command. Let's say you several files in the folder named, image1.jpeg, image2.jpeg, image3.jpeg etc. We want to rename all of these files to image1.jpg, image2.jpg etc respectively.

There are several different ways you can do this. One way is to use the for loop in bash to iterate over the files and then change the extensions of each file. You could use other commands such as find to filter the files as well. But we will use the for loop in these examples.

We will see this in steps. The first part is to iterate (or list) all the files that you want to act on. In this example it will be just iterating all the files in the current directory that have a .jpeg extension.

for fx in *.jpeg; do echo $fx; done

Now, we will need find a command that will let us replace just part of the file name, the extension. basename is one such command that will let you split the file names by suffix. So, we can use this to print out just the filename without the suffix.

$ basename image1.jpeg .jpeg

The above will print out just image1 which is the file name without any extension. We can now combine this with the for loop to rename the files.

for fx in *.jpeg; do mv $fx `basename $fx .jpeg`.jpg; done
linux-batch-rename-files.png

If you are using bash, then you can use some advanced bash scripting to do perform the same action without the basename command.

for fx in *.jpeg; do mv $fx ${fx%.jpeg}.jpg; done
linux-bash-rename-files.png

The above example is probably the best way to rename multiple files from command line, especially once you have mastered the syntax of substitutions in bash. You can create more complex scripts that will handle more complex renaming requirements.