How do I extract the IPv4 IP Address from the output of ipconfig

I'd like to isolate "192.168.1." and have that saved to a variable

Use the following batch file (test.cmd):

@echo off
setlocal
setlocal enabledelayedexpansion
rem throw away everything except the IPv4 address line 
for /f "usebackq tokens=*" %%a in (`ipconfig ^| findstr /i "ipv4"`) do (
  rem we have for example "IPv4 Address. . . . . . . . . . . : 192.168.42.78"
  rem split on : and get 2nd token
  for /f delims^=^:^ tokens^=2 %%b in ('echo %%a') do (
    rem we have " 192.168.42.78"
    rem split on . and get 4 tokens (octets)
    for /f "tokens=1-4 delims=." %%c in ("%%b") do (
      set _o1=%%c
      set _o2=%%d
      set _o3=%%e
      set _o4=%%f
      rem strip leading space from first octet
      set _3octet=!_o1:~1!.!_o2!.!_o3!.
      echo !_3octet!
      )
    )
  )
rem add additional commands here
endlocal

Notes:

  • The value you want is saved in _3octet
  • Remove the echo which is there for debugging
  • Replace rem add additional commands here with your "network ping"

Example usage and output:

F:\test>ipconfig | findstr /i "ipv4"
   IPv4 Address. . . . . . . . . . . : 192.168.42.78

F:\test>test
192.168.42.

Further Reading

  • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
  • enabledelayedexpansion - Delayed Expansion will cause variables to be expanded at execution time rather than at parse time.
  • for /f - Loop command against the results of another command.
  • ipconfig - Configure IP (Internet Protocol configuration)
  • set - Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.
  • setlocal - Set options to control the visibility of environment variables in a batch file.
  • variables - Extract part of a variable (substring).