Windows – batch file to strip numbers from filename and pad to two digits

batch-filewindowswindows-command-prompt

I have a text file with a list of server names (servers.txt) that looks something like this:

server1
server2
server3

I have a feeling this can be done with the FOR command as I use that to perform an action on each name in the file, but I'm not quite sure how to use the delimiters to accomplish this.

for /F "tokens=*" %%G in (servers.txt) do (  
  SET machinenum = <magic here>
  ECHO %machinenum%
)

expected output

01
02
03

Best Answer

Here's how you would do it in your example. Make the token larger (1-8) for however many servers you have. If you don't know how many servers you'll have, it would be a lot easier to put each server on it's own line.

for /f "tokens=1-3 delims=server" %%a in ('type server.txt') do set machinenum=0%%a0%%b0%%c
echo %machinenum%

If this is an actual batch file, use the double %%. If it's from the command line, use a single %