How to use regex quantifiers to rename multiple files with zmv?

Posted on

Problem :

I have the following files in a single directory:

1-1 - different text for each file here.txt
1-2 - different text for each file here.txt
.
.
1-9 - different text for each file here.txt
1-10 - different text for each file here.txt
1-11 - different text for each file here.txt
1-12 - different text for each file here.txt
.
.

I want to rename the files all at once (using zmv running in zsh) to:

1-01 - different text for each file here.txt
1-02 - different text for each file here.txt
.
.
1-09 - different text for each file here.txt
1-10 - different text for each file here.txt
1-11 - different text for each file here.txt
1-12 - different text for each file here.txt

Here’s what I tried: zmv '1-([0-9])(*)' '1-0$1$2'

This results in following file names:

1-01 - different text for each file here.txt
1-02 - different text for each file here.txt
.
.
1-09 - different text for each file here.txt
1-010 - different text for each file here.txt
1-011 - different text for each file here.txt
1-012 - different text for each file here.txt
.
.

So I thought I’d change the find pattern to zmv '1-([0-9]{1})(*)' '1-0$1$2' to match only files with a single digit after the hyphen, but this doesn’t work
(I just get zmv:232: no matches found: 1-([0-9]{1})(*)).

What am I doing wrong? Is this even possible using zmv or should I use something like sed in a for loop or something like that?

Solution :

This should work for you:

zmv '1-([0-9])( *)' '1-0$1$2'

or

zmv '1-([0-9])([^0-9]*)' '1-0$1$2'

You just need to make the match include only one digit followed by a space or non-digit. With the way you had it, it was matching one digit followed by anything.

Leave a Reply

Your email address will not be published.