I need to extract the Major , Minor and Revision numbers from a string and to achieve this I'm trying to split a string in a batch file using a '.' character as the delimiter.
For ex: If the user enters 1.0.2 in the command prompt I should be able to extract
- 1 - Major version,
- 0 - Minor version and
- 2 - Revision
I'm trying to use the FOR command to achieve this, but just not getting through. Can anyone help me out with the extracting part
@ECHO OFF & SETLOCAL
set /p "ReleaseVersion=Please specify the software release version : "
:nextVar
for /F "tokens=1* delims=." %%a in ("%ReleaseVersion%") do (
set %%a
set ReleaseVersion=%%b
)
if defined ReleaseVersion goto nextVar
@PAUSE
I recently discovered an interesting trick that allows to split a string based on a delimiter without using
for
command, so I couldn't resist the temptation to post it here. This question also represent a different way to use my method (split string in more than 2 different variables). Here it is:Further details at this post.
EDIT: Some explanations added
You may read a full description of the split method here. However, this answer also use an
if defined Minor
command in order to change the variable name from "Minor" to "Revision" after Minor variable value was set; this point can be easily understood if you remove the@echo off
command and review the trace output.Although this method allows to define more than two variables with different names, it is somewhat cumbersome to insert a
& (if defined prevVar set v=newVar)
command for each additional variable. For example:The splitting of a string in several different variables can the achieved in a better way with the aid of a subroutine:
The split method used in this subroutine is explained with detail in this post, but I copied here the relevant parts and modified they for this example:
Note that the
call set "!p!v[!i!]!p!=%"
part is a nested replacement that is executed with each one of the substrings of the original replacement. This way, this method is comprised of three stages:call set "!p!v[!i!]!p!=1"
,call set "!p!v[!i!]!p!=0"
, etc.call set "%v[1]%=1"
,call set "%v[2]%=0"
, etc.set "Major=1"
,set "Minor=0"
, etc.EDIT 2018/02/18: New method added
I developed a new method that allows to assign values to different variables using just one line. This method is new in the sense that allows to split two variables in the same line/replacement:
Not have enough reputation to comment. Posting an answer instead :)
There's a helpful resource: http://ss64.com/nt/syntax-substring.html
Use this approach to extract substrings from the string as you want.
UPDATE:
Get position of a character in a string
As you get the dot position, you can use the above described approach to extract necessary parts from the input string.
Here you go...
Input/output: