Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
654 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
    )
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...