-2

I have the following file, which defined a version number of a project, which I am using in many places, like CMake files, python scripts, and other configurations. My only struggle is how can I read this in my batch file in windows? The syntax seems a little bit weird and I have to struggle with it for a few hours now and still can't figure it out.

Version.txt:

VERSION_MAJOR 09
VERSION_MINOR 02
VERSION_PATCH 21
VERSION_SUFFIX rc

What I am trying to do, is to use the values of the variables above in my bat script, something like this:

BatchScript.bat

VERSION_MAJOR = @VERSION_MARJO_FROM_FILE (e.g 09)
VERSION_MINOR = @VERSION_MARJO_FROM_FILE (e.g 02)
aschipfl
  • 33,626
  • 12
  • 54
  • 99
pureofpure
  • 1,060
  • 2
  • 12
  • 31
  • 1
    The `SET` command is used to assign values to a variable. The `FOR` command with the `/F` option is used to read a file. Please show us a [mcve] of the code you are trying to use. – Squashman Aug 02 '21 at 13:20
  • In `BatchScript.bat` use the command line `for /F "usebackq tokens=1*" %%I in ("Version.txt") do set "%%I=%%J"` and after that line there are defined the environment variables `VERSION_MAJOR` with string value `09` and `VERSION_MINOR` with string value `02` and `VERSION_PATCH` with string value `21` and `VERSION_SUFFIX` with string value `rc`. Run in a command prompt window `for /?` for help on this command. The string comparisons can be done with `if` using operator `==`. See also [Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files](https://stackoverflow.com/a/47386323/3074564). – Mofi Aug 02 '21 at 13:32
  • It is of course also possible to use `for /F "usebackq tokens=1*" %%I in ("Version.txt") do set "%%I_FROM_FILE=%%J"` to define the four environment variables with names ending with `_FROM_FILE`. But better would be using `for /F "usebackq tokens=1*" %%I in ("Version.txt") do set "FILE_%%I=%%J"` to define the four environment variables with `FILE_` at beginning of their names. You know why this is better if you add to the batch file as next line `set FILE_` to output all environment variables with name beginning with `FILE_` and their current values. – Mofi Aug 02 '21 at 13:36

1 Answers1

0

I found how to do it.

for /f "tokens=1* delims= " %%i in (version.txt) do (
  if %%i==VERSION_MAJOR call set version_major%%=%%j
  if %%i==VERSION_MINOR call set version_minor%%=%%j
  if %%i==VERSION_PATCH call set version_patch%%
  if %%i==VERSION_SUFFIX call set version_suffix%%
)
pureofpure
  • 1,060
  • 2
  • 12
  • 31
  • 1
    As Mofi showed you in his code comments above you do not need to use an `IF` command to do what you need to do. Nor do you need the `CALL` command. – Squashman Aug 02 '21 at 16:18