Check “IF” condition inside FOR loop (batch/cmd)

batch-file

The code I need to implement in a Windows batch file is like this (it is currently in Perl):

while(<file>)
{
   if($_ =~ m/xxxx/)
   {
      print OUT "xxxx is found";
   }
   elsif($_ =~ m/yyyy/)
   {
      next;
   }
   else
   {
      ($a,$b) = split(/:/,$_);
      $array1[$count] = $a;
      $array2[$count] = $b;
      $count++;
   }
}

My questions are:

  1. Is this level of complexity possible in Windows batch files?
  2. If so, how can I put an If condition
    inside a for loop to read a text
    file?

Thanks for your attention. If you know the answers, or have any ideas/clues on how to reach the answer, please share them.

EDIT: I am working in Windows. I can use only whatever is provided with Windows by default and that means I cant use Unix utilities.

Best Solution

Putting if into for in general is easy:

for ... do (
    if ... (
        ...
    ) else if ... (
        ...
    ) else (
        ...
    )
)

A for loop that iterates over lines can be written using /f switch:

for /f "delims=" %%s in (*.txt) do (
    ...
)

Regexps are provided by findstr. It will match against stdin if no input file is provided. You can redirect output to NUL so that it doesn't display the found string, and just use its errorlevel to see if it matched or not (0 means match, non-0 means it didn't). And you can split a string using /f again. So:

set count=0
for /f "delims=" %%s in (foo.txt) do (
    echo %%s | findstr /r xxxx > NUL
    if errorlevel 1 (
        rem ~~~ Didn't match xxxx ~~~
        echo %%s | findstr /r yyyy > NUL
        if errorlevel 1 (
            rem ~~~ Didn't match yyy ~~~
            for /f "delims=; tokens=1,*" %%a in ('echo %%s') do (
                 set array1[!count!]=%%a
                 set array2[!count!]=%%b
                 set /a count+=1
            )
        )
    ) else (
        echo XXX is found
    )
)