Commands.page Logo

How to Batch Rename Files in Ubuntu by Replacing Substrings

This guide explains how to efficiently rename multiple files in Ubuntu by replacing specific text substrings. You will learn to use the command-line tool rename for quick substitutions and bash loops for custom scripting. These methods ensure you can organize large directories without manually renaming each file individually.

Using the Rename Command

The most efficient method is using the rename utility, which is based on Perl regular expressions. It is often pre-installed on Ubuntu. To replace a substring in all text files within the current directory, open your terminal and navigate to the folder containing your files.

Run the following command to replace “old_text” with “new_text”:

rename 's/old_text/new_text/' *.txt

Always perform a dry run before executing the actual rename operation to prevent data loss. Add the -n flag to see what changes would occur without applying them:

rename -n 's/old_text/new_text/' *.txt

If the output looks correct, remove the -n flag to execute the changes.

Using a Bash Loop

If the rename tool is not available, you can use a standard bash loop with parameter expansion. This method is built into the shell and requires no additional packages. Navigate to your target directory in the terminal.

Execute the following loop to replace substrings across all files:

for f in *; do mv "$f" "${f//old_text/new_text}"; done

This script iterates through every file in the directory. The syntax ${f//old_text/new_text} replaces all occurrences of the substring in the filename variable. Ensure you wrap variables in quotes to handle filenames containing spaces correctly.

Verifying Changes

After running either command, list the directory contents to confirm the new filenames. Use the ls command to view the updated list:

ls -l

If you made a mistake, you can reverse the process by running the same command with the old and new text swapped, provided you act quickly before further changes are made. Always back up important data before performing batch operations.