This is how I usually do it (manually on the shell):
rename left- left-0 left-?.png # for 0-9
rename left- left-0 left-??.png # for 00-99
rename left- left-0 left-???.png # for 000-999
# result left-0000.png - left-9999.png
This is easy to do in an interactive shell session... just repeat the last command with one additional
However, with a large number of files, you'll eventually end up with a too long list of arguments. And obviously it's not the most efficient choice, as it ends up renaming the same file multiple times (left-1.png -> left-01.png -> left-001.png -> ...).
Also there are two flavors for
rename about, one with perl regular expressions and one without. Depending on distro you end up with
perl-rename or other names for them. Basically it renders any script using the
rename command unportable since you never know what to expect.
I'm using the the util-linux rename and your question is actually one of their examples, from the man page:
Given the files foo1, ..., foo9, foo10, ..., foo278, the commands
rename foo foo00 foo?
rename foo foo0 foo??
will turn them into foo001, ..., foo009, foo010, ..., foo278.
Which is the more efficient method (each file renamed only once) but you have to figure out the correct distribution of
??? or you'll end up with a wrong result.
To me, the inefficient method is the more practical one, on an interactive shell, when dealing with a reasonable small set of files.
The advantage of
rename over scripting it yourself is that it doesn't have to spawn one
mv process for each file, or as in your case, a sub-script just to figure out a filename. It's not clear what has more overhead, the process spawning, or repeated renaming, and I'm too lazy to benchmark it.
Actually the answer you linked already contains the "optimal" solution at the very end... using perl-rename:
rename 's/\d+/sprintf("%04d",$&)/e' *.png
Well, one can argue about the regular expression, but the point is, it's possible to do it all in one go, without unnecessary
mv, or spawning of processes. If you still need to improve on that, write a tool that reads directory contents directly instead of using shell globbing (which sorts, which is slow) and performs the renaming as needed.
Maybe that's actually the answer you linked to and maybe that's why you're getting downvoted. ;)