Commands.page Logo

Rename Multiple Files Matching Pattern Ubuntu Command

This guide explains how to efficiently rename multiple files in Ubuntu using a single command line instruction. You will learn about the powerful rename utility and basic shell loops that allow you to modify filenames matching specific patterns without manual effort. By following these steps, you can batch process file names quickly and safely within your terminal environment.

Using the Rename Command

The most effective tool for this task is the rename command, which uses Perl regular expressions. It is often pre-installed on Ubuntu, but you can install it via sudo apt install rename if missing. The basic syntax replaces a specific text string across all matching files in the current directory.

To change all .txt extensions to .bak, use:

rename 's/.txt/.bak/' *.txt

Testing Changes Before Execution

Always verify your pattern before applying changes permanently. Add the -n flag to perform a dry run. This displays what changes would occur without actually renaming any files.

rename -n 's/old/new/' *old*

Review the output to ensure the logic is correct. Once confirmed, remove the -n flag to execute the rename operation.

Alternative Method Using a Loop

If the rename utility is unavailable, you can use a bash for loop with the mv command. This method iterates through files matching a pattern and renames them individually within a single line of code.

for f in *.jpg; do mv "$f" "image_${f}"; done

This command prepends “image_” to every JPEG file in the directory. Ensure you quote variables properly to handle filenames containing spaces.