Get a string from other file and use it for the variable in your Windows Batch file

Summary

Get a string from other file and use if for the variable in your Windows Batch file. In this example, we'll get application version number string from build.gradle file that used for Android application development.

Sample build.gradle file

We'd like to get version string 1.0.0 from this file.

android {
    compileSdkVersion 28
    buildToolsVersion '28.0.3'
    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0.0"
...

Sample batch file

for /f "tokens=2" %%i in ('findstr "versionName" build.gradle') do (
    set VERSION=%%i
)
set VERSION=%VERSION:"=%
echo VERSION=%VERSION%

This script doing below.

  1. findstr command get a line which has versionName string from build.gradle. Above example, we got versionName "1.0.0".
  2. We got 2nd column string from a line versionName "1.0.0" and set it to the variable VERSION.
    *We can do it by the option /f tokens=2 of for command. This option split string to some tokens and save 2nd token value to variable %%i. Above example, we got "1.0.0".
  3. Remove double quotes.
    *%VERSION:"=% means replace double quotes characters " in the VERSION variable with empty string.

Output

We got output below when execute sample batch file.

VERSION=1.0.0