0

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.

2 Answers 2

2

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

printf "%0*d\n" ${CNT} 5 
Sign up to request clarification or add additional context in comments.

6 Comments

No, I didn't. This is useful information too, but indeed I think the seq solution is more natural to the use case in question.
@uli_1973 ... but seq is an external tool, while printf is a Bash built-in.
@BenjaminW. good point, but not relevant since I only need that for personal use.
@uli_1973 Sure, but answers here are not just for whoever asked them, but for everybody who finds them later when encountering a similar problem, so ideally they employ universal best practices.
So what is the * parameter to printf? An answer should include an explanation, not an unanswered question.
|
1
  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 

2 Comments

2. was a mis-copying, in the original example at the top of my question I had it correct. 1. I did try the curly braces - however, for some reason I only put them around the $CNT ...
The indices are of course also variables, but they didn't cause any problems to me. seq -f "%0${CNT}g" $FROM $TO works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.