I am having issues with a problem accomplished very easily in most languages but I can't seem to figure it out in batch. I want to extract the last character of a string. In pseudo code..
if var1.substring(var1.length, -1) = "0"
do something
In english...if the last character in the string is 0 then...
To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string.
Just use a negative number starting at -1 to select a character in the string. In the case of the index at -1 Python will select the last index of the string.
set var=%var:~-1%
see SET /?
from the prompt for docco.
@ECHO OFF
SETLOCAL
SET var=abcd
SET var2=%var:~-1%
CALL :show "-1"
SET var2=%var:~-2%
CALL :show "-2"
SET var2=%var:~-3%
CALL :show "-3"
SET var2=%var:~1%
CALL :show "1"
SET var2=%var:~2%
CALL :show "2"
SET var2=%var:~3%
CALL :show "3"
SET var2=%var:~0,1%
CALL :show "0,1"
SET var2=%var:~0,2%
CALL :show "0,2"
SET var2=%var:~0,3%
CALL :show "0,3"
SET var2=%var:~0,-1%
CALL :show "0,-1"
SET var2=%var:~0,-2%
CALL :show "0,-2"
SET var2=%var:~0,-3%
CALL :show "0,-3"
SET var2=%var:~1,-1%
CALL :show "1,-1"
SET var2=%var:~1,-2%
CALL :show "1,-2"
SET var2=%var:~1,-3%
CALL :show "1,-3"
GOTO :eof
:show
echo Test with "var:~%~1" : var=%var% var2=%var2%
GOTO :eof
Results:
Test with "var:~-1" : var=abcd var2=d
Test with "var:~-2" : var=abcd var2=cd
Test with "var:~-3" : var=abcd var2=bcd
Test with "var:~1" : var=abcd var2=bcd
Test with "var:~2" : var=abcd var2=cd
Test with "var:~3" : var=abcd var2=d
Test with "var:~0,1" : var=abcd var2=a
Test with "var:~0,2" : var=abcd var2=ab
Test with "var:~0,3" : var=abcd var2=abc
Test with "var:~0,-1" : var=abcd var2=abc
Test with "var:~0,-2" : var=abcd var2=ab
Test with "var:~0,-3" : var=abcd var2=a
Test with "var:~1,-1" : var=abcd var2=bc
Test with "var:~1,-2" : var=abcd var2=b
Test with "var:~1,-3" : var=abcd var2=
For your IF
statement, try
IF "%var:~-1%"=="0" (dosomething) else (dosomethingelse)
Batch does not use C style logic, so you really have to think differently for much of it.
That said, String -right appears to be what you want: http://www.dostips.com/DtTipsStringManipulation.php#Snippets.RightString
%str:~-1%
That will get you the last character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With