Skip to content

Renaming multiple files in one go

When dealing with a large amount of files is not uncommon to want to execute some operation to all of them at once.

Here are some ways to rename a large group of files in one single terminal command, using different utilities. Pick the one that fits your environment!

Batch renaming in Powershell ​

This method will work out of the box on any Windows system with powershell (or Linux system with pwsh installed).

powershell
ls *.txt | rename-item -NewName {$_.name -replace "OldStringOfText","ReplacementText"}

More documentation here.

Using perl rename script ​

In some distributions there's a rename perl script (sometimes under the name/alias of perl-rename) that accepts a perl expression as first parameter to alter the name of the files. This can be very powerful if you know your way through a perlexpr, but the most common example below would be sufficient 99.99% of the time.

sh
rename "s/OldStringOfText/ReplacementText/" *.txt

More documentation here.

The script can also be obtained from cpan (perl -MCPAN -e 'install File::Rename'), or copied from here.

Using util-linux rename utility ​

Sometimes the rename command installed in your Linux (or cygwin/msys) system might be a different one, not the perl script, but rather the one included in the util-linux package. If that's the case (check rename --help if in doubt) then you may use it as below:

sh
rename "OldStringOfText" "OldStringOfText" *.txt

More documentation here.

Using Emacs dired mode ​

If you have GNU Emacs installed in your system (and you can have it installed, be it in Linux, Windows, Mac OS or any other of the supported OS for it), you can do the following:

  1. Open any directory (eg. Ctrl-x then d) and it'll display the list of files in "dired" mode.

  2. While in dired, press Ctrl-x then Ctrl-q to switch to a writtable mode (wdired) in which you can edit the text buffer to modify the filenames.

  3. You can edit the files just by typing, or you can use any editting commands such as search-and-replace (Alt-%, or typing query-replace on the Alt-x prompt) to edit the list of filenames.

  4. In order to save the changes press Ctrl-c then Ctrl-c (that's the same shortcut two times); or otherwise press Ctrl-c then ESC to cancel.

More documentation here.

Personal page