Search code examples
windowsstringbatch-filecmdstring-parsing

How do I get the number at the end of a string in batch?


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

Solution

  • 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 /?