Searching for a line

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
ragavhee
Posts: 2
Joined: 03 May 2011 01:39

Searching for a line

#1 Post by ragavhee » 03 May 2011 02:07

Hi,

I am very new to batch scripting and i need to search a file and assign the value of a particular line to a variable. The file contents are like this.

Variable name : NextFiscalYr1
Server name : chnveltss04
Application name :
Database name :
Variable value : FY13

Variable name : Fcst_Wk
Server name : chnveltss04
Application name : Plan_UAT
Database name :
Variable value : Wk1

Variable name : NextScenario
Server name : chnveltss04
Application name : Plan_UAT
Database name :
Variable value : LE_Wk2

How do i search for variable value where variable name is Fcst_Wk and then assign Wk1 to a variable?

Regards,
Ragav.

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: Searching for a line

#2 Post by dbenham » 03 May 2011 11:54

For this example, assume data is in data.txt in current directory.

Assuming that neither name nor value will ever contain a space or colon, then the following should work:

Code: Select all

@echo off
set VAL=
set SAVE=
for /f "tokens=2,3 delims=: " %%a in ('findstr /b /c:"Variable name : " /c:"Variable value : " "data.txt"') do (
  if %%a==name if "%%b"=="Fcst_Wk" (set SAVE=true) else set SAVE=
  if defined SAVE if %%a==value set VAL=%%b
)

The value is assigned to the VAL variable.
VAL will be undefined if any of the following are true:
  • The chosen Variable name is not found
  • The section for the chosen Variable name is missing the Variable value line
  • The Variable value line exists but has a blank value

Dave Benham

ragavhee
Posts: 2
Joined: 03 May 2011 01:39

Re: Searching for a line

#3 Post by ragavhee » 04 May 2011 01:36

Hi Dave,

Thanks for your response. I modified the script like below. The exact string is as in the script

Code: Select all

@echo off
set VAL=
set SAVE=
for /f "tokens=2,3 delims=: " %%a in ('findstr /b /c:"Variable name    : " /c:"Variable value   : " "load.txt"') do (
  if %%a==name if "%%b"=="Fcst_Wk" (set SAVE=true) else set SAVE=
  if defined SAVE if %%a==value set VAL=%%b
)


I run this batch file from a VB script like this.

Retval = Shell("\\chnveltss04\HPMacro\Volume_Transfer\Tran IN_OUT.bat ", 0)

How can i take the output of the variable VAL and assign to a variable in VB?

FYI, there are few irrelevant lines above and below the example i have provided.

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: Searching for a line

#4 Post by dbenham » 04 May 2011 06:45

Why use batch to extract the value if you are already using VB Script? The FileSystemObject and TextStream objects allow you to open and read a text file directly within VB Script.

Dave

Post Reply