Given a set of files numbered 1.ext 2.ext .. n.ext files, how can they best be renamed 01.ext 02.ext .. 0n.ext (or 00n.ext, etc.)?
rename comes with most distributions.
William O’Higgins Witteman’s thread ∞
On 2/26/07, William O’Higgins Witteman <william.ohiggins utoronto.ca> wrote:
I have a mess of sequentially numbered files (1.png, 2.png … 824.png)
that I’d like to pad the filenames of so that they sort prettily
(0001.png, 0002.png … 0824.png). I thought to use the rename command,
but I’m not getting the results I need, and Google didn’t help.Here’s what I tried with rename:
rename -n "s/(\d)\.png/000$1png/" *This would only catch the first 9 files, but I no that I had the right
method.I can certainly whip up a quick program in Python or Perl (I could
probably learn enough Ruby in half an hour too, or Lua, or C, or …
you get the picture) but I was curious where I was going wrong with
rename. Any suggestions? Thanks.
1 ∞
Well, here’s something that echos the commands to the command line:
for i in `seq 12`; do f1=`printf "%d.png" $i` f2=`printf "%03d.png" $i` echo "mv $f1 $f2" done mv 1.png 001.png mv 2.png 002.png mv 3.png 003.png mv 4.png 004.png mv 5.png 005.png mv 6.png 006.png mv 7.png 007.png mv 8.png 008.png mv 9.png 009.png mv 10.png 010.png mv 11.png 011.png mv 12.png 012.png
Change the last line as shown below to get the renaming to actually
take place…
for i in `seq 12`; do f1=`printf "%d.png" $i` f2=`printf "%03d.png" $i` mv $f1 $f2 done
2 ∞
There might be a faster way, but I always solve this problem with a
for loop (in Bash–not sure how the syntax differs for other shells).
for i in [1-9].png; { mv $i 000$i; } for i in [1-9][0-9].png; { mv $i 00$i; } for i in [1-9][0-9][0-9].png { mv $i 0$i; }
3 ∞
There are at least two different versions of rename, and they do
not take the same syntax.
A shell script (this is bash/ksh93 specific) is straightforward:
for file in [1-9]*.png do newname=0000$file newname=${newname: -8} ## POSIX: newname=${newname#"${newname%????????}"} mv "$file" "$newname" done
My solution ∞
It will end up here: https://github.com/spiralofhope/shell-random/tree/master/live/sh/scripts/renumber-files.sh

ported from rough notes
this is inspiration for my finally making my own script to solve this nuisance.