Set a variable to 3 digits

Solved
Patrick33 -  
dubcek Posted messages 18627 Registration date   Status Contributor Last intervention   -
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

Anonymous user
 
hello,

printf '%03d\n' 1 12 113 1114
2
Patrick33
 
What are all the numbers after the printf for?
0
Anonymous user
 
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
0
Patrick33
 
No, I understood that. I'm talking about those after the command "1 12 113 1114"
0
Patrick33
 
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
0
Patrick33
 
I was missing the $(), it's fixed, thanks for your help!
0
blux Posted messages 5028 Registration date   Status Moderator Last intervention   3 455
 
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"
0
Patrick33
 
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.
0