Batch-rename files easily with `rename`

alvinb

Alvin Bryan

Posted on October 27, 2020

Batch-rename files easily with `rename`

I use the rename action in macOS Finder when I need simple operations. For example, changing a file extension from .PNG to .png or replacing underscores with hyphens. For more complex stuff, like lowercasing, or removing a range of characters, Finder becomes too tedious.

That’s where the rename command comes in. It lets you use regular expressions and looks like this: rename -f '[regex]' [files].

Right off the bat, you want to remember the -n or --dry-run option. It’s super useful to test out what the resulting files will be without actually renaming them.

Here’s how you would replace all the double dashes with single ones:

~/Export ❯❯❯ rename -f 's/--/-/' * -n
'Example--1.png' would be renamed to 'Example-1.png'
'Example--2.png' would be renamed to 'Example-2.png'
'Example--3.png' would be renamed to 'Example-3.png'
'Example--4.png' would be renamed to 'Example-4.png'
Enter fullscreen mode Exit fullscreen mode

The * in the command above means “do this on all files in the current folder.” You can use glob patterns to specify target files. So, to rename only .png files, you’d write rename '[regex]' *.png

As I said, regular expressions.

You write them like this s/[old]/[new]/ or y/[old]/[new]/ without the square brackets.

In our command, s/ regexes are used for 1-to-1 character mapping while y/ regexes are for more complex replacements involving character ranges. I mostly use y/ regexes because as I said earlier, there’s Finder. Here we go, practical examples.

Replacing dashes with underscores: rename -f 's/-/_/' *

It gets really powerful when you can work on character ranges:

  • rename -f 'y/a-z/A-Z/' * turns all lowercase into uppercase.
  • rename -f 'y/A-Z/a-z/' * turns all uppercase into lowercase

More real-world examples.

Turn filenames into URL-friendly "slugs" 🐌:
rename 'y/A-Z /a-z-/' *

Remove the last 𝒙 characters in a filename and replace them:
rename 's/.{𝒙}$/replacement/' *

In my case, Notion's Markdown export adds 34 random characters to every exported file. That's how I get rid of them:
rename 's/.{36}$/.md/' *.md

As usual, install it with Homebrew or apt-get: brew install rename or apt-get install rename.

💖 💪 🙅 🚩
alvinb
Alvin Bryan

Posted on October 27, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related