0

Is there a command that will return the position of a the first space found in a filename starting from the right?

Example:

"my filename.txt" would return 13 "my file name.txt" would return 9

Thanks

Wayne In Yak
  • 546
  • 1
  • 4
  • 21

3 Answers3

0

PowerShell:

PS C:\> $s = "test string 1"
PS C:\> $s.LastIndexOf(" ")
11
Bill_Stewart
  • 22,916
  • 4
  • 51
  • 62
0

There is no direct batch command, but it is not hard to compute. You can use find/replace to remove everything up through the first space. Then all you need do is compute the remaining length and add 1.

I recommend the good performing :strlen function

@echo off
setlocal enableDelayedExpansion
set "var=my filename.txt"
set "test=!var:* =!"
call :strlen pos test 
set /a pos+=1
echo result=%pos%
exit /b

:strlen <resultVar> <stringVar>
setlocal EnableDelayedExpansion
set "s=!%~2!#"
set "len=0"
for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
  if "!s:~%%P,1!" NEQ "" ( 
    set /a "len+=%%P"
    set "s=!s:~%%P!"
  )
)
endlocal & set "%~1=%len%"
exit /b
Community
  • 1
  • 1
dbenham
  • 127,446
  • 28
  • 251
  • 390
0
@ECHO Off
SETLOCAL
set "var=my filename.txt"
:: here call the function. returns "length"
CALL :mylength
ECHO Length is %length% ERRORLEVEL is %errorlevel%
GOTO :EOF

:mylength
setlocal
SET /a length=0
:mylenloop
IF "%var:~-1%" neq " " SET "var=%var:~0,-1%"&SET /a length+=1&GOTO mylenloop
endlocal&SET length=%length%
:: optional : set errorlevel to the length as well
EXIT /b %length%

This function returns the length of the string after the space. If you want to include the space, simply change SET /a length=0 to SET /a length=1.

You don't say what to do if there are no spaces in the string, but this solution works where there is more than one space.

Magoo
  • 77,302
  • 8
  • 62
  • 84