RetroCode UK

Published Date May 3, 2021 Reading Time ~2 minutes RSS Feed Linux Command Line

Bulk Rename Files

The default rename function on Arch is quite useful, but only has quite basic substitute options.

The format of the command is rename <search-text> <replace-text> file-glob

For this example, create a few example files with touch

rename .md .html *.md
rename test test00 *.html

The first command above changes the extension from “.md” to “.html”, and the second one adds a “00” after “test”. The files will end up as test001.html, test002.html and test003.html.

There are a few useful options that rename has; a good way to preview what might happen without actually changing any file names is to use the options -n (no action) and -v for verbose.

Here is an example:

rename -nv 00 '' *.html
`test001.html' -> `test1.html'
`test002.html' -> `test2.html'
`test003.html' -> `test3.html'

Another useful option is -i which is for interactive mode. This will prompt you to confirm each change in turn.

A more powerful alternative

There is a much more powerful alternative for rename is perl-rename (in some distributions this may be the default and actually called rename, but not for Arch)

sudo pacman -S perl-rename

This has perl regular expression type subsitution commands, and this first example capitalises all letters:

>> perl-rename -vn 'y/a-z/A-Z/' *.html
test001.html -> TEST001.HTML
test002.html -> TEST002.HTML
test003.html -> TEST003.HTML

A slightly more unconventional example here replaces all instances of t with s and s with a:

perl-rename -vn 'y/te/sa/' *.html
test001.html -> sass001.hsml
test002.html -> sass002.hsml
test003.html -> sass003.hsml

And finally a simple substituion example to update the extension again:

perl-rename -vn 's/.html$/.txt/' *.html
test001.html -> test001.txt
test002.html -> test002.txt
test003.html -> test003.txt