Arun AV
Arun AV

Reputation: 86

Not able to set the variable correctly in a batch script

I am reading a values from the xml file using batch , values are like Age="18" When the value is extracted i don't want the double quotes

for /f "tokens=2 delims= " %%b in ('type <file_name> ^| FIND "info" ) do (
echo %%b
set string =%%b

string = Age="18" ( getting error here)

in the info tag <info Name="xxx" Age="18"></info>

i need only the value 18 to be stored in a variable

Need assistance

Upvotes: 0

Views: 952

Answers (2)

Mofi
Mofi

Reputation: 49096

This task can be done with:

for /F "tokens=5 delims==> " %%I in ('%SystemRoot%\System32\findstr.exe /R /C:"<info .* Age=\"[0123456789][0123456789]*\"" "XmlFile.xml"') do echo %%~I& set "string=%%~I"

FOR executes in this case in background one more command process with %ComSpec% /c and the command line between ' appended as additional arguments. So executed is in background with Windows installed to C:\Windows:

C:\Windows\System32\cmd.exe /c C:\Windows\System32\findstr.exe /R /C:"<info .* Age=\"[0123456789][0123456789]*\"" "XmlFile.xml"

FINDSTR runs a case-sensitive regular expression search for a line containing <info containing the attribute Age and the attribute value being a number. The found line is output to handle STDOUT (standard output) of the background command process captured by FOR.

After started cmd.exe closed itself after findstr.exe terminated, FOR processes the captured output line by line with skipping empty lines.

The line is split up into substrings using = and > and space as string delimiters because of delims==> . The fifth substring is the value of attribute Age enclosed in double quotes which is assigned to the specified loop variable I because of tokens=5. The double quotes are removed because of using modifier %~I.

To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.

  • echo /?
  • findstr /?
  • for /?
  • set /?

Upvotes: 1

Compo
Compo

Reputation: 38613

Instead of choosing the 2nd token with   as the delimiter, you probably want the 4th token using the " as a delimiter:

 @For /F Tokens^=4^ Delims^=^" %%G In ('^""%__AppDir%find.exe" /I "<info "^<"filename.txt"^"') Do @Set "age=%%G"

You may also wish, for robustness, to match a more unique pattern. You can do that by choosing findstr.exe instead of find.exe:

@For /F Tokens^=4^ Delims^=^" %%G In ('^""%__AppDir%findstr.exe" /IR "<info\ Name=\"[a-Z]*\"\ Age=\"[0-9]*\">" "filename.txt"^"') Do @Set "age=%%G"


Please note that the pattern I have used for the age, allows for superscript digits. However, this scenario is unlikely ever to be encountered, in your actual case, so I figured that this pattern should suffice.

Upvotes: 1

Related Questions