uli_1973
uli_1973

Reputation: 721

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.

Upvotes: 0

Views: 356

Answers (2)

Walter A
Walter A

Reputation: 19982

I think you want seq, but did you know the * operator in printf?

printf "%0*d\n" ${CNT} 5

Upvotes: 2

oguz ismail
oguz ismail

Reputation: 50750

  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

Upvotes: 1

Related Questions