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

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:
:h(“head”) keeps the directory part, likedirname:$ print ${f:h} talks
Like
dirname, it returns.when there’s no directory part:$ g=robot.png $ print ${g:h} .
:t(“tail”) keeps the filename part, likebasename:$ print ${f:t} robot.png
:r(“root”) drops the extension:$ print ${f:r} talks/robot
:e(“extension”) keeps only the extension:$ print ${f:e} png
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:
for i in *.pngloops over the PNG files in the current directory, with each filename in$i.magick $i …converts each file, with ImageMagick picking the formats based on the file extensions. (No quotes needed around$i: unlike Bash, Zsh doesn’t word-split unquoted variables, so filenames with spaces are safe.)${i:r}.webpbuilds the output filename.:rremoves the file extension, turningrobot.pngintorobot, so appending.webpmakesrobot.webp.
Learn how to make your tests run quickly in my book Speed Up Your Django Tests.
One summary email a week, no spam, I pinky promise.
Related posts:
- Zsh: select files with arbitrary code in
(e)or+glob qualifiers - Zsh: list recently modified files with
(m0)glob qualifiers - Zsh: select generated files with
(om[1])glob qualifiers
Tags: zsh