Search code examples
bashsequencestring-formatting

Bash: Zero-pad a number with a variable for the digit count


I need to zero-pad a sequence of numbers in a loop in Bash. I know how to do it with

seq -f "%03g" 5

or the comparable printf approach, also

for index in {003..006}

The problem I did not find an answer to is that I need the number of digits to be a variable:

read CNT
seq -f "%0$CNTd" 3 6

Will return an error

seq: das Format »%0“ endet mit %

I have not found any way to insert a variable in a format string or any other way to produce a zero-padded sequence where the number of digits comes from a (user-provided) variable.


Solution

    1. A variable name (CNT) should be enclosed in curly braces when it is followed by a character (d) which is not to be interpreted as part of its name,
    2. seq doesn't support %d, you should use %g.
    $ read -r CNT
    $ seq -f "%0${CNT}g" 3 6
    00003
    00004
    00005
    00006