I am currently working on a batch file that is supposed to read a version number from another file.
Basically, I just need to extract the string from the other document and get the number from it (number changes over time).
set dir=..\folder1\file1.vcxproj
:: I want to get a string from %dir% with a specific beginning and then extract the version number from it
set string=... ("<PlatformToolset>*")
set vernum=... ("..>v142<..)
Thats what I want to achieve:
echo %string%
<PlatformToolset>v142</PlatformToolset>
echo %vernum%
142
I hope I could describe my problem. Unfortunately I have little experience with cmd and it is difficult for me to articulate myself in this respect.
I hope someone can still help :)
CodePudding user response:
dir
is a poor name for a variable for two reasons. First dir
is a keyword in batch, and then it implies that it's a directory when it seems to be a file.
Use set "var1=value"
for setting STRING values - this avoids problems caused by trailing spaces. Quotes are not needed for setting arithmetic values (set /a
)
So presuming that what you're doing is to extract the 142
from the string
<PlatformToolset>v142</PlatformToolset>
found in the file dir
(please change that name)
for /f "tokens=1,2delims=<> " %%b in ('type "%dir%"') do if "%%b"=="PlatformToolset" set "vernum=%%c"
set "vernum=%vernum:~1%"
note that the location and quote type ('
or "
) are critical.
The for
reads each line of the file and analyses that line, assigning the first "token" (1) to %%b
and the second (2) to %%c
.
The line is regarded as being
<delimiter sequence><token1><delimiter sequence><token2><delimiter sequence><token3><delimiter sequence><token4>
A delimiter sequence is one or more of any of the characters specified in the delims=
option; in this case, <, > and Space
So - where %%a
(token 1) is PlatformToolset
, we want to assign %%c
(token 2) to vernum
so vernum
will become v142
with a file containing the test line you've posted.
And the hieroglyphics behind the set
command is explained by set /?
from the prompt - it takes the value in vernum
, starting at "character 1" (where the character numbering starts at 0) and assigns the result to the variable vernum
for more detail about for
gymnastics, see for /?
from the prompt.