J. Doe
J. Doe

Reputation: 15

batch extract part of a variable (substring)

I have programs with some of them having 64bit versions: foo.exe bar.exe bar64.exe etc. So wanted to extract 2 last characters from a filename (without extension) and do something then...

@echo off
setlocal enableextensions enabledelayedexpansion

for /f "tokens=1,2 delims=." %%G in ('dir /b *.exe') do (
set _test=%%G
set _result=!_test:~-2!

echo !_result!
)

endlocal
exit

This works well if the number of characters to extract IS NOT 2. If it is 2 then echo goes crazy. Is it me doing things wrong or some bug?

Upvotes: 1

Views: 267

Answers (1)

user6811411
user6811411

Reputation:

You did use the whole file name, since .exe is four chars the error you describe shouldn't occur. To avoid unexpected behavior simple prepend the name with any two chars.

@echo off&setlocal enableextensions enabledelayedexpansion
for /f "tokens=*" %%G in ('dir /b *.exe') do (
    set "_test=__%%~nG"
    set _result=!_test:~-2!
    echo:!_result!
)

Edit To avoid echo status being reported, use a different command separator than a space.

Upvotes: 1

Related Questions