首页 > 解决方案 > How to split string in batch-file

问题描述

I want to get all the port that running on my windows I tried

for /f "tokens=2" %a in ('netstat -aon ^| findstr LISTENING ^| find "127.0.0.1:"') do @echo %~nxa

The results

127.0.0.1:2375
127.0.0.1:8884
127.0.0.1:49326

How I can get only the ports : ( How I can do split by ":" )

2375
8884
49326

I tried also

    for /f "tokens=2" %e in ('netstat -aon ^| findstr LISTENING ^| find "127.0.0.1:"') do for /f "tokens=2 delims=:" %b in ("%e") do @echo %b

but then I got echo also for the command for example
C:\Users\>for /F "tokens=2 delims=:" %b in ("127.0.0.1:2375") do @echo %b
2375

C:\Users\>for /F "tokens=2 delims=:" %b in ("127.0.0.1:8884") do @echo %b
8884

C:\Users\>for /F "tokens=2 delims=:" %b in ("127.0.0.1:40447") do @echo %b
40447

C:\Users\>for /F "tokens=2 delims=:" %b in ("127.0.0.1:49326") do @echo %b
49326

C:\Users\>for /F "tokens=2 delims=:" %b in ("127.0.0.1:49334") do @echo %b
49334

C:\Users\>for /F "tokens=2 delims=:" %b in ("127.0.0.1:51975") do @echo %b
51975

C:\Users\>for /F "tokens=2 delims=:" %b in ("127.0.0.1:56502") do @echo %b
56502

标签: windowsbatch-filesplit

解决方案


为了确保对从第一个 for 循环中获得的每个项目应用分隔符检查,您需要编写一个如下所示的子例程并将值传递给它,即您正在检索的每个 IP:Port 组合。然后在子例程中,您可以提取作为 %1 传入的值,然后在分隔符上进行拆分。

@echo off
for /f "tokens=2" %%a in ('netstat -aon ^| findstr LISTENING ^| find "127.0.0.1:"') do (call :subroutine %%a)
:subroutine
   set x=%1
   for /f "tokens=1,2 delims=:" %%a in ("%x%") do @echo %%b

推荐阅读