1

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

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

and the output is:

Default Gateway...: x.x.x.x

I need a single command, and the output should be only x.x.x.x.

Ansgar Wiechers
  • 175,025
  • 22
  • 204
  • 278
Mr. Prabhu
  • 35
  • 2
  • 12

2 Answers2

2

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
Loïc MICHEL
  • 22,418
  • 8
  • 68
  • 94
  • Really I want single line command like this. Thank you. However when I execute this in cmd prompt it says " %%i was unexpected at this time" – Mr. Prabhu Jun 25 '13 at 11:33
  • I fixed the error. instead of %%i we need to use %i. This resolves my problem. Thank you very much. – Mr. Prabhu Jun 25 '13 at 11:37
  • 2
    use `%%i` in batch but `%i` in interractive mode – Loïc MICHEL Jun 25 '13 at 11:43
  • I used this to omit the space at the beginning. Perhaps there is a simpler way: for /f "tokens=12 delims=: " %i in ('ipconfig ^| findst r /i "Default gateway" ^| findstr [0-9]') do echo %i – Goodies Feb 11 '15 at 17:41
1

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...

James L.
  • 8,959
  • 3
  • 34
  • 74