Search code examples
linuxbashzshseqzero-pad

How to zero-pad numeric variables in zsh (and maybe also bash?)


In zsh, when I have to create a bunch of files with zsh, I usually do something like:

for x in $(seq 1 1000); do .....; done

This works fine, it gives me files with names foo-1.txt .. foo-1000.txt.
However, these files do not sort nicely, so I would like to zero-pad the $x variable, thus producing names of foo-0001.txt .. foo-1000.txt.

How to do that in zsh? (and bonus question, how to do it in bash?)


Solution

  • Use the -w flag to seq (in any shell):

    $ seq -w 1 10
    01
    02
    03
    04
    05
    06
    07
    08
    09
    10