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

3.8k Views Asked by At

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

2

There are 2 best solutions below

1
Magoo On BEST ANSWER
@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.

0
ryan On

@Magoo

Think I have it sorted

set string= = 1 

without error I have modified code as below. I am getting an output although a "The syntax of the command is incorrect" error when loop tries

set lastchar== 1

that's the reason I have added 2>nul to suppress error

@ECHO Off
SETLOCAL

SET string=abcd = 1
:loop1
SET lastchar=%string:~1,1% 2>nul
SET string= %string:~2%
IF NOT "%string%"=="" GOTO loop1

ECHO last char=%lastchar%