Answered Parsing Text in Command Line

  • Wednesday, January 30, 2013 11:35 PM
     
      Has Code
    Hi all,

    My goal is to extract the IP Addresses from this Command:

    wmic PATH Win32_NetworkAdapterConfiguration where (DNSDomain is not null) Get IPAddress /value | find "="

    Which gives me this output:

    IPAddress={"10.30.143.64","fc82::7933:455e:62v3:ac74"}

    In command line all outputs are text, so I'm trying to parse it with a FOR Loop:

    @echo off
    SETLOCAL
    FOR /F usebackq^ delims^=^" %%a IN (`wmic PATH Win32_NetworkAdapterConfiguration where ^(DNSDomain is not null^) Get IPAddress /value ^| find "="`) DO call :subroutine %%a %%b %%c %%d
    
    :subroutine
    echo %1
    echo %2
    echo %3
    echo %4

    Notice the absence of double quotes in the options, because I need the double quote itself as the delimiter.

    Now the reseult becomes like this:

    IPAddress
    {
    c
    d
    ECHO is off.
    ECHO is off.
    ECHO is off.
    ECHO is off.


    ok, maybe there's something wrong with the options, let's remove it altogether:

    @echo off
    SETLOCAL
    FOR /F %%a IN ('wmic PATH Win32_NetworkAdapterConfiguration where ^(DNSDomain is not null^) Get IPAddress /value ^| find "="') DO call :subroutine %%a %%b %%c %%d
    
    :subroutine
    echo %1
    echo %2
    echo %3
    echo %4

    Then I got this:

    IPAddress
    {"10.30.141.64"
    "fd82::2268:4e5a:65d3:ca74"}
    c
    ECHO is off.
    ECHO is off.
    ECHO is off.
    ECHO is off.

    Now two things I've observed:

    1) The parsing is definitely wrong.
    2) The FOR loop iterated two times on the output from wmic, which should be one line (and FOR /F is supposed to remove all blank lines).


    Anyone kind enough to point out my mistake?  Thanks.

All Replies

  • Thursday, January 31, 2013 12:24 AM
     
     Answered Has Code
    @echo off
    SetLocal
    set cmd=wmic PATH Win32_NetworkAdapterConfiguration where (DNSDomain is not null^^) Get IPAddress /value
    FOR /F "tokens=2 delims==" %%a IN ('%cmd% ^| find "=" ^| find ","') DO set Addresses=%%a
    set addresses=%addresses:~2,50%
    set addresses=%addresses:~0,-2%
    for /F "tokens=1,2 delims=," %%a in ('echo %addresses%') do set IPv4=%%a & set IPv6=%%b
    for /F %%a in ('echo "%IPv4%') do set IPv4=%%~a
    for /F %%a in ('echo %IPv6%"') do set IPv6=%%~a
    echo IPv4=%IPv4% IPv6=%IPv6%
    
    The problem with advanced parsing in batch files is that it's usually a matter of trial and error. Not nice. Try the code above. It's easy to debug because it performs its actions in a number of structured steps.
  • Thursday, January 31, 2013 3:54 AM
     
     
    Wonderful.  Thank you very much.  I would've done this with a one liner in Powershell if not for backward compatibility for some old junks.  Or should I say I've been spoiled by PS :)

    Thanks again.