Set a variable to 3 digits

Solved
Hello forum user,
I’m here to ask whether it’s possible to force a variable that contains a number to be a certain number of spaces.
For example, if I set varA=001 and then increment this variable, its value will be 2 whereas I’d like it to be 002.
Thanks in advance for your answers!

2 answers

  • Votes
  • Date
  • Descending date
  1. hello,

    printf '%03d\n' 1 12 113 1114
    1. What are all the numbers after the printf for?
    2. it's the format! XD
      d : indicates an integer
      3 : indicates the desired right shift
      0 : indicates to pad with zeros on the left

      see man 3 printf
    3. No, I understood that. I'm talking about those after the command "1 12 113 1114"
    4. The command works but not when I enter it into a variable.
      varB=printf '%03d\n' $varA
      It's probably a silly mistake because I'm just starting with the shell
    5. I was missing the $(), it's fixed, thanks for your help!
  2. Moderator
    Hi,

    what's it for?
    Because if the goal is just display, then you handle it digitally internally and when you want to display, you format...

    --
    A+ blux
     "Les cons, ça ose tout.
    C'est même à ça qu'on les reconnait"
    1. I have a series of about a hundred files named in the form nomdufichier_000.txt. The number at the end of the name increments. I want to perform an operation on these files one after another in increasing order, so I’d like to use a variable to do, for example, "grep -n 'toto' *$mavariable.txt"; however, this variable, when I increment it, gets simplified. That is, it will do 001 + 1 = 2 and not 002, so on the next pass it will search for the file *2.txt which no longer points to a single unique file.