Search code examples
filebatch-fileif-statementfor-loopcall

Analyze a file and call function


I wrote a batch script and I have a little problem.

Basically, I have a file "ip_file.txt" with IP (% ip_file%).
My script parses this file, and, based on the IP, call a particular program.

Here's how I wrote the script, but it does not work.

REM START SCRIPT BASE

for /f %%i in (%ip_file%) do ( 
IF %%a.%%b.==10.10 call :script_1 %%i 
IF %%a.%%b.==192.168 call :script_2 %%i 
) 
else ( call :script_0 %%i) 

REM END SCRIPT BASE

Any idea?


Solution

  • Assuming the contents of the file referenced by %ip_file% is a list of IPv4 addresses (or at least that each line begins with an IPv4 address), you can use tokens and delims to split on ..

    @echo off
    setlocal
    
    REM // START MAIN RUNTIME
    
    set "ip_file=path\to\ip_file.txt"
    
    for /f "usebackq tokens=1-4 delims=." %%a in ("%ip_file%") do ( 
    
        if "%%a.%%b"=="10.10" (
    
            call :script_1 %%a.%%b.%%c.%%d
    
        ) else if "%%a.%%b"=="192.168" (
    
            call :script_2 %%a.%%b.%%c.%%d
    
        ) else call :script_0 %%a.%%b.%%c.%%d
    )
    
    goto :EOF
    REM // END MAIN RUNTIME
    
    :script_0 <ip>
    rem // catch-all
    goto :EOF
    
    :script_1 <ip>
    rem // handle 10.10 addresses
    goto :EOF
    
    :script_2 <ip>
    rem // handle 192.168 addresses
    goto :EOF
    

    It should also be noted, when you call :label where label begins with a colon, you are calling a subroutine within the same batch script. If you are indeed calling external batch scripts, leave off the colons.