Alex Rivera | Logout

check "IF" condition inside FOR loop (batch/cmd)

Asked 2009-07-22T08:51:04.117
9

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++;
   }
}

How can I put an If condition inside a for loop to read a text file using a batch script file?

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

Edit
Report

2 Answers

18

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
    )
)
answered 2009-07-22T20:35:01.870
1

here's a rough vbscript equivalent of your Perl script.

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\file.txt"
Set objFile = objFS.OpenTextFile(strFile)
Dim array1()
Dim array2()
count=0
Do Until objFile.AtEndOfStream
    strLine = objFile.ReadLine
    If InStr(strLine,"xxxx") >0 Then
        WScript.Echo " xxxx is found."
    Else
        s = Split(strLine,":")
        ReDim Preserve array1(count)
        ReDim Preserve array2(count)
        array1(count)=s(0)
        array2(count)=s(1)
        count=count+1
    End If 
Loop
'print out the array elements
For i=LBound(array1) To UBound(array2)
    WScript.Echo array1(i)
    WScript.Echo array2(i)
Next

For your information, there is always the Perl for windows which you can use, without having to learn another language.

answered 2009-07-22T09:15:31.337

Your Answer