Search code examples
batch-filevariablescmdsetwindows-nt

Get last character of a string from a variable Windows NT batch CMD


Trying to make my batch compatible across various windows versions including Windows NT.

I need to return the last character of a variable. Normally I would use %foo:~-1% to return although this does not work on Windows NT.

I have read WinNT version of set /? to no avail.

Using %foo:~x,1% where x is the position of last character won't work for me as the variable length will change.

I thought of running a script to check str length with one of many methods, then running !foo:~%x%,1! but to my knowledge the reason I cant get this to work is lack of delayed expansion in WinNT and a lot of coding for something I'm hoping to be a simple fix.

Any ideas how to tackle this?

Thanks


Solution

  • @ECHO Off
    SETLOCAL
    
    SET string=abcd
    :loop1
    SET lastchar=%string:~0,1%
    SET string=%string:~1%
    IF NOT "%string%"=="" GOTO loop1
    
    ECHO last char=%lastchar%
    
    SET string=wxyz
    :loop2
    SET lastchar=%string:~99,1%
    SET string=q%string%
    IF "%lastchar%"=="" GOTO loop2
    
    ECHO last char=%lastchar%
    
    GOTO :EOF
    

    I can no longer remember whether the set "var=value" syntax worked on NT. If it does, that syntax is preferred to skirt the invisible-trailing-spaces problem.

    and the findstr approach:

    set string=pqrs
    for %%a in (a b c d ... o p q r s ...z A ... Z etc.) do echo %string%|findstr /e /L /C:"%%a">nul do if not errorlevel 1 set lastchar=%%a
    

    Naturally, if you apply /i to the findstr then you can omit one case of alpha-characters.