Substrings in Batch Files

In my last post I stated that batch files need better string support, that was before I realized that you could actually get substrings from variables. Here is an excerpt from the set command documentation (i.e. set /?):

May also specify substrings for an expansion.

    %PATH:~10,5%

would expand the PATH environment variable, and then use only the 5 characters that begin at the 11th (offset 10) character of the expanded result.  If the length is not specified, then it defaults to the remainder of the variable value.  If either number (offset or length) is negative, then the number used is the length of the environment variable value added to the offset or length specified.

    %PATH:~-10%

would extract the last 10 characters of the PATH variable.

    %PATH:~0,-2%

would extract all but the last 2 characters of the PATH variable.

Therefore perhaps a simpler way to generate a filename which includes the date would be:

echo %DATE%
echo %DATE:~4,2%%DATE:~7,2%%DATE:~10,4%

Output:

Thu 09/01/2005
09012005

PS: I know I didn't localize this solution ;) It is here to demonstrate how to get substrings in batch files.

[Cross posted on my personal blog]

1 Comment

  • Thank, the solution are running.

    @echo off
    set waitm=2
    set/a waits=10
    set seg=60

    :loop_m
    set min2=%time:~4,1%
    echo Minutes at Position 2 value = %min2% (and waitM value = %waitm%)
    if %min2% == %waitm% goto loop_s
    goto loop_m

    :loop_s
    set/a sec2=%time:~6,2%
    echo Seconds at Position 2 value = %sec2% (and waitS value = %waits%)
    if %sec2% LSS %waits% goto bucle
    goto loop_m


    :bucle
    c:
    cd \ows\queues
    queue-deamon.exe
    echo Ping -n %seg% 127.0.0.1 (Wait 1 minute)
    Ping -n %seg% 127.0.0.1 > nul
    cls
    goto loop_m

Comments have been disabled for this content.