Link to home
Start Free TrialLog in
Avatar of LeTay
LeTay

asked on

format an environment variable in DOS (Windows)

I write a DOS "script" (.cmd) where I want to recuperate the content of an environment variable containing a small number and format it in 3 digits (left padding with 0)
So if for example the environment variable is Number and contains 3, I want to have later on in another variable, says Formatted, a string 003
How can I do this in a cmd ?
Avatar of Steve Knight
Steve Knight
Flag of United Kingdom of Great Britain and Northern Ireland image

The easiest way is to add 1000 or a big enough number to it to fill in any missing 0's and then take the right n characters.  You can do that as:
@echo off
set /p varA=Enter number:
set /a varA=varA +1000
set varA=%varA:~-3%
echo varA is now %varA%


You can do various changes to strings using the %variable:~x,x% and %variable:x=y% syntaxes which you can see more info in set /? from a cmd.exe prompt

Steve
i.e. varA = 6, it then becomes 1006 and then 006.
if varA=1291 then it becomes 2291 and then 291
Steve
Avatar of LeTay
LeTay

ASKER

Excellent
I just forgot to mention the following
The script has as input argument the name of the output variable to set to
so ?
Avatar of LeTay

ASKER

Says that the final script name is Pad.cmd
I call Pad as follows
Pad 12 MyVar
and at exit, the variable MyVar should contain 012
How do you handle this ? %1 inside contains 12 and %2 contains MyVar ?
Thanks
ASKER CERTIFIED SOLUTION
Avatar of Steve Knight
Steve Knight
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You can't use %%2:~-3% so did all the changes to tempvar then assigned tempvar into your variable name.

You should add I suppose

set tempvar=

just before the exit /b to remove the temp var too.