如何在批处理文件中分割字符串

时间:2019-05-13 15:20:48

标签: windows batch-file split

我想获取所有在Windows上运行的端口 我尝试过

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

结果

127.0.0.1:2375
127.0.0.1:8884
127.0.0.1:49326

我如何只能获取端口:(如何通过“:”分割)

2375
8884
49326

我也尝试过

    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

1 个答案:

答案 0 :(得分:1)

要确保对从第一个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