Zsh: manipulate filenames with modifiers like :r (root) and :e (extension)

Transform your filenames…

Zsh modifiers are a family of suffixes that transform words as they’re expanded. Several of them are dedicated to slicing up filenames, replacing fiddly calls to dirname, basename, and friends. Let’s take a look at them now!

The filename modifiers

Four modifiers cover most filename manipulation. Take this variable assignment to a path:

$ f=talks/robot.png

These modifiers each return a different part of the path:

Modifiers can be chained, applying left to right. For example, :t:r does “tail” then “root”, reducing a path to its bare name:

$ print ${f:t:r}
robot

An example with :r

I recently wanted to convert some PNG images into the smaller WebP format for a little game I’m making. I used ImageMagick’s magick command, with this loop using :r to build the output filenames:

$ for i in *.png; do magick $i ${i:r}.webp; done

Breaking that down:

Fin

Bring on the mods,

—Adam


Learn how to make your tests run quickly in my book Speed Up Your Django Tests.


Subscribe via RSS, Twitter, Mastodon, or email:

One summary email a week, no spam, I pinky promise.

Related posts:

Tags: