Although you can use renaming utilizes to rename those annoying numbers in filenames, but I always have to double-check with --help of rename almost every single time, I just couldn’t remember what arguments should be used and how they should be written.

The need of padding zeros does not happen very often, but I still need that once in a while, so having a simple and quick script for such task could come in handy and also make sure it is safe to run it.

I call this script: 1to001.py. Its filename clearly tells what it does.

Note

On 2014-01-04, it’s moved to GitHub from Gist and renamed to 1to001. You can install it directly with pip install 1to001.

A quick example:


$ touch 1.txt 100.txt
$ 1to001.py *.txt
+ 001.txt
? ++
perform padding (y/n)? y
1.txt -> 001.txt

An example for error:


$ 1to001.py 'book 1.txt' 'chapter 10.txt'
Error 3: different amount of fields and/or at least one non-number field does not have same content

It knows if the filenames have different pattern, if so, it won’t do anything.

Little complicated example:


$ 1to001.py 'book 1 chapter 1' 'book 10 chapter 4' 'book 5 chapter 12'
+ book 01 chapter 01
? + +
+ book 10 chapter 04
? +
+ book 05 chapter 12
? +
perform padding (y/n)? n

You can see it can pad more than one number field and it detects automatically. You don’t need to write any pattern for matching and replacement texts. This script does those for you. You only need to read the output diff text, which shows you where the zeros would be padded.

Still using:


$ rename 'book ' 'book 0' 'book '?' '*

Or:


$ for fn in 'book '?' '*; do mv "$fn" "${fn/book /book 0}"; done

You must be freaking losing your mind! Even if you are a shell master, one day it’s going to get you, ending up only messing some filenames up if you are lucky; or unfortunately, overwriting files by filename collisions.

It has not happened to me—at least not this way, but if I am still trying my luck, it definitely will and make me mad someday.

You don’t want to like this guy.

Play safe or have fun smashing up something!