Joey's solution works, but the character to search for is hard-coded and is relatively slow.
Below is a parameterized function that is quick and can find any character (except nul) inside the string. I pass the name of the variables containing the string and the character, instead of string literals, so that the function easily supports all characters.
@echo off setlocal set "test=/name1/name2/name3" set "char=/" ::1st test simply prints the result call :lastIndexOf test char ::2nd test stores the result in a variable call :lastIndexOf test char rtn echo rtn=%rtn% exit /b :lastIndexOf strVar charVar [rtnVar] setlocal enableDelayedExpansion :: Get the string values set "lastIndexOf.char=!%~2!" set "str=!%~1!" set "chr=!lastIndexOf.char:~0,1!" :: Determine the length of str - adapted from function found at: :: http://www.dostips.com/DtCodeCmdLib.php
No major changes are required to create a more general function :indexOf , which takes an additional argument that determines which detection to find. A negative number may indicate a search in reverse order. So 1 can be 1st, 2nd, -1 last, -2 penultimate, etc.
source share