Extract part of a string using a batch file

May 25, 2011 at 17:35:50
Specs: Windows XP
I have a DOS batch file that calls an exectuable. The executable does its thing and prints the following in the cmd window: SNMPv2-SMI::enterprises.30679. = STRING: "0.0"

What I want out of that long string is the value at the end: "0.0"

I've tried sending the output to a file and then use a For loop to try to parse the line and isolate
what I want. But I've not been successful. Here's one of my tries:

FOR /F "eol=; tokens=1* delims= " %%i in (output.txt) do @echo %%i %%j %%k

That splits the line in two at the equal sign, and prints %k as part of the second token.

See More: Extract part of a string using a batch file

Report •

May 25, 2011 at 19:31:40
Test this

for /f "tokens=1-3*" %%1 in (output.txt) do (
    echo %%4

Please come back & tell us if your problem is resolved.

Report •

May 26, 2011 at 10:06:43
Wow! That worked. Thank you very much. Perhaps, if you have time, you could
explain how that FOR loop is working or point me to a resource (book, website,
etc.) that explains it. From what I was able to find on the internet, the "tokens"
argument defined the lines in the file that are to be parsed. But it appears that
that is not always the case.

Report •

May 26, 2011 at 16:35:13
Thank you for coming back to report your success. The For loop is pretty basic, here's a wee bit of a breakdown:

Your file consists of just one line
SNMPv2-SMI::enterprises.30679. = STRING: "0.0"

Viewing that shows the line can be extracted into four variables using the space(s) as the best delimiter.

Space is one of the default Delims(deliminators) so there is not need to specify it.

Tokens=1-3* means that variable %%1 will consist of the line from the left to the first space SNMPv2-SMI::enterprises.30679.

Variable %%2 will consists of the line from the first to second space

Variable %%3 will consist of the line from the second to third space

Variable %%4 will contain the rest of the line which is what you want

Echoing %%4 displays the result.

My command of English is not so good, hope the above makes sense to you.

There are many many good sources of batch scripting advice, both online and in printed forms. I tend to recommend the online sites of Rob Van Der Woude such as http://www.robvanderwoude.com/batch... and http://www.robvanderwoude.com/ntfor...

Please note that I have not affiliation with Rob Van Der Woude except as a user of the information provided by him.

Good luck, don't hesitate to come back with any queries which you might have, some very good scripting gurus surf these C.Net forums. You can also enter the command /? at the command prompt to display the help screen so that For /? will display lots of info on the For command.

Please come back & tell us if your problem is resolved.

Report •

Related Solutions

Ask Question