Bala
Bala

Reputation: 223

Batch script to look for a variable in a file and read its value to a variable

I am looking for a batch script to search for a variable in a file and read its value. Example: My text file has lines as

VERSION=6.0.196.0
CS_VERSION=6.0

I want my batch script to find the variable VERSION and read its value (6.0.196.0) to a variable PVERSION in my batch script and then value of CS_VERSION (6.0) to another variable DVERSION.

How can i do this? searched for some similar questions but they are giving me outputs as:

PVERSION==VERSION=6.0.196.0
DVERSION==CS_VERSION=6.0.

I just need output as

PVERSION=6.0.196.0
DVERSION=6.0.

Please help and thanks in advance.

Upvotes: 1

Views: 1989

Answers (1)

Alex K.
Alex K.

Reputation: 175826

One way (read each line, delimiting on = and capturing the lhs/rhs to %%A & %%B);

@echo off
setlocal EnableDelayedExpansion
for /F "eol= tokens=1,2 delims==," %%A in (the.file) do (
    if "%%A"=="VERSION" (
        set version=%%B
    ) else if "%%A"=="CS_VERSION" (
        set cs_version=%%B
    )
)

echo VERSION is %version%
echo CS_VERSION is %cs_version%

Test;

@echo off
@(
echo 1
echo 2
echo 3
echo 4
echo 5
echo 6
echo 7
echo 8
echo 9
echo 10
echo 11
echo 12
echo 13
echo 14
echo 15
echo 16
echo 17
echo VERSION=6.0.196.0
echo CS_VERSION=6.0
) > the.file

setlocal EnableDelayedExpansion
for /F "eol= tokens=1,2 delims==, skip=17" %%A in (the.file) do (
    if "%%A"=="VERSION" (
        set version=%%B
    ) else if "%%A"=="CS_VERSION" (
        set cs_version=%%B
    )
)

echo VERSION is %version%
echo CS_VERSION is %cs_version%

Upvotes: 3

Related Questions