-1

I'm writing a batch command file that uses the local machine's hostname, and I need to extract the number at the end of the string. How do I get the number at the end of a string in batch?

INPUT:

W2008R2T001
W2008R2T002
W2008R2T003
W8_1_901
QATEST84
QATEST85
QATEST86

DESIRED OUTPUT:

001
002
003
901
84
85
86
  • If you want a "write code for me" service, there's always elance.com and similar contracting sites. What have you got so far, and how doesn't it work? – TessellatingHeckler Aug 19 '15 at 17:01
  • Googling this question did not help me very much, unless you mean pointers on how to parse an entire string, one character at a time. – user3117967 Aug 19 '15 at 22:23

2 Answers2

1

Here is a little batch script just written by myself.

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "HostName=W2008R2T001"
set /p "HostName=Enter a host name (default %HostName%): "
call :GetNumber "%HostName%"
if "%Number%" == "" (
    echo This host name has no number at end.
) else (
    echo Found number at end of host name is: %Number%
)
pause
endlocal
goto :EOF

:GetNumber
set "Number="
set "StringToParse=%~1"
set "Digits=0123456789"
:CheckLastChar
if "!Digits:%StringToParse:~-1%=!" EQU "%Digits%" goto:EOF
set "Number=%StringToParse:~-1%%Number%"
set "StringToParse=%StringToParse:~0,-1%"
if "%StringToParse%" NEQ "" goto CheckLastChar
goto :EOF

This batch file lets the user enter a string. For this string the subroutine GetNumber is called using delayed environment variable expansion enabled already at beginning of main batch routine to copy all digits at end of the string to parse in right order to an environment variable Number.

The main routine evaluates the value of the environment variable Number and continues processing accordingly.

For details on how this works, open a command prompt window, execute there the following commands, and read all help pages output for each command.

  • call /?
  • goto /?
  • if /?
  • set /?
Mofi
  • 46,139
  • 17
  • 80
  • 143
  • This is the kind of rigor I was hoping to avoid, but I understand, this is in batch-command, not PowerShell. This is a very elegant solution, and it works. – user3117967 Aug 19 '15 at 22:21
1

I realized that the data you want is the last one separated by a certain delimiter. In your example, the delimiters are T_ and there are a maximum of 3 parts in W8_1_901 line. The Batch file below get the data you want accordingly to these rules:

@echo off
setlocal EnableDelayedExpansion

for /F "tokens=1-3 delims=T_" %%a in (test.txt) do (
   for %%A in (%%a %%b %%c) do set "last=%%A"
   echo !last!
)

If may be more delimiters, insert they in delims=T_ part. If may be more parts in a line, modify the "3" in tokens=1-3 part and add more letters in %%a %%b %%c part.

Aacini
  • 65,180
  • 12
  • 72
  • 108