Nifty command lines: rename
This post is part of the Nifty Command Lines series.
The rename
command allows you rename multiple files at once. It makes complex operations like lowercasing accessible with a single line. For simpler operations, like changing extensions from .PNG
to .png
, I usually reach for the action in macOS Finder.
How does rename
work?
It lets you use regular expressions to batch-rename files. It looks like this:
rename -f '[regex]' [files]
Dry run
You want to remember the -n
or --dry-run
option. It shows you what the resulting files will be without affecting them.
Example: Replace 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'
The *
in the command above means “all files in the current folder.” You can use glob patterns to target specific files.
To rename only .txt
files, you’d write rename -f '[regex]' *.txt
Regular expressions
You write your regexes like this s/[old]/[new]/
or y/[old]/[new]/
without the square brackets.
s/
regexes are used for 1-to-1 character replacement, while y/
regexes are for complex replacements involving ranges1. Here are some general 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.
Real-world examples
Turn filenames into URL-friendly “slugs” 🐌:
rename -f 'y/A-Z /a-z-/' *
Remove the last 𝒙 characters in a filename and replace them:
rename 's/.{𝒙}$/replacement/' *
Remove the 34 random characters that Notion’s exporter adds to Markdown files:
rename 's/.{36}$/.md/' *.md
Installation
Install it with Homebrew or apt-get: brew install rename
or apt-get install rename
.
Footnotes
-
If you want to dig into these (I never did), know that they’re Perl regexes. ↩