Bash: How to Rename Extension of Multiple Files


You can use the following syntax in Bash to replace the extension of multiple files at once:

for name in *.txt; do mv -- "$name" "${name%.txt}.text"; done

This particular example replaces any file extension that currently has a .txt extension with a .text extension instead.

Note that the mv operator in Bash allows you to rename and move files.

In this example, we use the mv operator to rename the file extensions.

The following example shows how to use this syntax in practice.

Example: How to Rename Extension of Multiple Files in Bash

Suppose that we would like to replace any file in our current directory that has a .txt extension with a .text extension instead.

To view the names of each file in the current folder, we can use the ls statement:

We can see that the current folder has the following files:

  • out_1.txt
  • out_2.txt
  • out_3.txt

Suppose that we would like to replace the .txt extension in each file with a .text extension instead.

We can use the following syntax to do so:

for name in *.txt; do mv -- "$name" "${name%.txt}.text"; done

The following screenshot shows how to use this syntax in practice:

Bash replace extension of multiple files

Notice that the .txt extension has been replaced with .text in each of the files in the folder.

The files now have the following names:

  • out_1.text
  • out_2.text
  • out_3.text

Note that any file names without .txt as the extension will simply be left unchanged.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Replace Text in String
Bash: How to Replace Specific Line in File
Bash: How to Replace Multiple Characters in String

Leave a Reply