How to split command output in Windows command prompt?

后端 未结 2 506
青春惊慌失措
青春惊慌失措 2021-01-16 14:36

Is there a split command in Windows, to split command output? My command is:

ipconfig | findstr /i \"Default gateway\" | findstr [0-9]


        
相关标签:
2条回答
  • 2021-01-16 15:04

    On my computer, there are two gateways returned, one for IPv4 and one for IPv6. The findstr doesn't distinguish between them. However, for me IPv4 is returned before IPv6. This batch file extracts the IP address for the gateway from the findstr output:

    @echo off
    
    setlocal ENABLEDELAYEDEXPANSION
    
    for /f "tokens=2 delims=:" %%i in ('ipconfig ^| findstr "Default gateway"') do (
      if not defined _ip set _ip=%%i
    )
    for /f "tokens=1 delims= " %%i in ("!_ip!") do (
      set _ip=%%i
    )
    
    echo !_ip!
    
    endlocal & set yourvar=%_ip%
    

    I split it into two separate for commands (instead of nesting the for commands) so that I could just grab the first 'gateway' returned from the findstr. The result has a leading space, so the 2nd for command removes the leading space. The & set yourvar=%_ip% at the end is how you pass a local variable outside of the local block, but you don't have to use that...

    0 讨论(0)
  • 2021-01-16 15:13

    there is not exactly a split function, but you can use FOR to accomplish what you want :

    for /f "tokens=2 delims=:" %%i  in ('ipconfig ^| findstr /i "Default gateway" ^| findstr [0-9]') do echo %%i
    
    0 讨论(0)
提交回复
热议问题