Search and replace filenames

Josh Sherman
1 min read
Command-line Interface

Recently, while working with a bunch of files, I came to realize that I needed to rename every single file. Not just that, I only needed to rename a small bit of the filename. If I was working with a document, I wound have leveraged a “search and replace” feature, but since this was files, I reached for my trusty command-line.

The filenames in question don’t really matter, what happens is that I wanted to take a file that was named like this:

some-great-filename-1.ext

And rename it to something like this:

some-amazing-filename-1.ext

There was no way in hell that I was going to do this manually in my file explorer since it was over 100 files!

When I originally approached this, I ended up throwing a loop into the mix that would generate a series of mv commands that used sed to do the string replacement on the destination filename.

This worked great and made for a fun one-liner, but was also overkill once I had discovered the rename command that I wasn’t aware existed initially.

The rename command is quite similar to mv in terms of usage and some of the available options (like -i, --interactive which will prompt you when overwriting files and keeps you safe).

Where rename is different than mv is that it takes an expression to match against and a replacement to use before the filename / pattern that will be used to match files.

A simple example would be renaming a bunch of files in a directory from one file extension to another, something that mv can’t do with multiple files:

rename .ext1 .ext2 *.ext1

For my scenario with the aforementioned filenames, you can create some files to follow along at home like this:

mkdir /tmp/joshtronic-rename
touch /tmp/joshtronic-rename/some-great-filename-{1..100}.ext

And then rename all of the files like so:

rename great amazing /tmp/joshtronic-rename/some-great-filename-*.ext
Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

Related Articles