Ubuntu – Sequential renaming of files

batch-renamecommand lineperlregexrename

I found an answer for zero-padding numerical filenames which works fine for renaming filenames as follows :

1.jpg > 00001.jpg
2.jpg > 00002.jpg
9.jpg > 00009.jpg

That uses the following command:

rename 's/\d+/sprintf("%05d", $&)/e' *.jpg

But my filenames aren't numeric. They are an alphanumeric sequence, like: a.jpg, b.jpg, c.jpg...... m.jpg.

In a similar way to the original question, I want to rename these so they display in the correct sequence. How do I do this?

Best Answer

You can zero-pad letters too, you just need to alter my original command slightly to:

rename 's/\w+/sprintf("%05s", $&)/e' *.jpg

We're basically just saying, replace the first "word" (numbers and letters) with a zero-padded string. It's very similar to the original, it's just slightly different. This version wold work for the original problem.

You could expand it into a .+ match (to zero pad everything), but then you might need to handle the extension on top.

Test harness:

$ mkdir test; cd test; touch {a..d}.jpg 1.jpg
$ rename 's/\w+/sprintf("%05s", $&)/e' *.jpg
$ ls
00001.jpg  0000a.jpg  0000b.jpg  0000c.jpg  0000d.jpg