Skip to main content

Zero padding shell snippets

I was looking for a way to zero-pad a number sequence in bash. While the internet was helpful as usual, one particular post had lots of examples in its comments, very neat stuff.

Of course, with so many differeant approaches, this called for a benchmark! :-)

$ time bash padding_examples.sh bash41 1000000 > /dev/null
real    7m38.238s
user    3m7.056s
sys     0m7.884s

$ time   sh padding_examples.sh printf 1000000 > /dev/null
real    1m39.314s
user    0m41.244s
sys     0m2.064s

$ time   sh padding_examples.sh    seq 1000000 > /dev/null
real    0m10.883s
user    0m5.016s
sys     0m0.040s
So, seq(1) is of course the fastest - if it's not installed, use printf.

Update: with bash-4.0, the following is also possible:
$ time echo {01..1000000} > /dev/null
real    0m38.852s
user    0m14.948s
sys     0m0.260s
However, this will consume a lot of memory:
  PID USER      PR  NI  VIRT  RES  SHR S  %CPU %MEM    TIME+  COMMAND
23468 dummy     25   5  189m 186m 1380 R  43.1 14.9  0:28.48  bash