Akshayanti
Akshayanti

Reputation: 326

How to access a substring using Batch programming? Also, how to manipulate a string to use it as integer value using batch programming?

After I type

netsh wlan show interfaces
netsh wlan show interfaces > interface.txt

in my system's command prompt, I get the current connection profile. I am interested in seeking out the string part of 'Profile' Section after the ':' part from the interface.txt file.

I'd prefer the program to go searching for 'Profile' using findstr and then extract the string part in the same line so that the code generated could be reused. How do I go about it?

Also, how do I use string data from a text file for manipulating it as an integer data?

Sample output:

Upvotes: 0

Views: 66

Answers (2)

Stephan
Stephan

Reputation: 56180

for /f "tokens=1,* delims=:" %%i in ('netsh wlan show interfaces^|find "  Profile"') do set p=%%j
echo %p: =%
for /f "tokens=1,* delims=:" %%i in ('netsh wlan show interfaces^|find "  Receive rate"') do set r=%%j
echo %r:~1%

EDIT npocmaka's comment reminded me, that some values (e.g. "Physical Address") contain colons. Edited code to get those values complete.

Note: the values have a starting space; With adding space to delimiters, this could be avoided, but on the other hand, some descriptions have more than one word ("Network Type"), so this is problematic. So I decided to let them in and "postprocess" the variable instead.

Upvotes: 1

MichaelS
MichaelS

Reputation: 6032

You could simply split your string using FOR and : as delimeter. Say your sting is like

SET yourstring = something: somethingelse even more stuff and you want to access somethingelse

Then you can use this:

REM this is to get everithing on the right of :
FOR /F "tokens=2 delims=:" %%X IN ("%yourstring%") DO SET substring=%%X
REM this is to get the first token after the first white space
FOR /F "tokens=1 delims= " %%X IN ("%substring%") DO SET yourvalue=%%X

Now %yourvalue% will contain somethingelse.

To answer your second question:

If you want a string representing a number to be regarded as an integer you have to use SET /A varname=%stringWithTheInteger%. /A allows you to do arithmetic operations on variables.

Upvotes: 1

Related Questions