Aditya Verma
Aditya Verma

Reputation: 37

How to extract string in batch file?

I am trying to extract IP of source of Remote Desktop Connection using,

FOR /F "tokens=3 USEBACKQ" %%F IN (`netstat -n ^| find "3389" ^| find "ESTABLISHED" /c`) DO SET /A IP=%%F

ECHO %IP%

But this way the IP variable contains IP along with the port 192.168.174.129:47523.

How can I extract only the IP part?

I read about the substring functionality in batch but that requires the starting position aling with length but I can't be sure of starting position as last octet of IP might change from 129 to 29 or even 2.

Upvotes: 1

Views: 1829

Answers (2)

Compo
Compo

Reputation: 38623

Here's a quick example according to my comment, of using the appropriate delims. It additionally uses findstr.exe instead of find.exe, in order to use a single match string, instead of performing multiple pipes to the same utility.

@Echo Off
SetLocal EnableExtensions
Set "IP="
For /F "Tokens=4 Delims=: " %%G In ('%SystemRoot%\System32\NETSTAT.EXE -n 2^>NUL
 ^| %SystemRoot%\System32\findstr.exe /R
 /C:":3389[ ][ ]*[^ ][^ ]*[ ][ ]*ESTABLISHED"') Do Set "IP=%%G"
If Not Defined IP GoTo :EOF
Echo %IP%

In this case, findstr.exe searches for, and returns, lines output from the NETSTAT.EXE -n command which contain the string :3389 immediately followed by a sequence of one or more space characters, then one or more none space characters, then one or more space characters, then the case sensitive string ESTABLISHED.

Please note however that ESTABLISHED is most likely a language dependent string, so this is unlikely to work universally.

Upvotes: 2

arty
arty

Reputation: 61

FOR /F "tokens=3 USEBACKQ" %%F IN (`netstat -n ^| findstr "3389" ^| findstr "ESTABLISHED"`) DO (
  for /f "delims=:" %%a in ("%%F") do set IP=%%a
)
echo %IP%

I replace find to findstr because find not search text in my machine. The second FOR with delims=: split 192.168.174.129:47523 in two parts. First part is IP address.

Upvotes: 1

Related Questions