检查FOR循环内的"IF"条件(批处理/ cmd)

Ann*_*nna 5 batch-file

我需要在Windows批处理文件中实现的代码是这样的(它目前在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++;
   }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  1. Windows批处理文件中是否存在这种复杂程度?
  2. 如果是这样,我怎样才能在for循环中放入If条件来读取文本文件?

感谢您的关注.如果您知道答案,或者有任何关于如何找到答案的想法/线索,请分享.

编辑:我在Windows工作.我只能使用Windows默认提供的任何内容,这意味着我无法使用Unix实用程序.

Pav*_*aev 10

iffor一般很简单:

for ... do (
    if ... (
        ...
    ) else if ... (
        ...
    ) else (
        ...
    )
)
Run Code Online (Sandbox Code Playgroud)

for,超过线迭代可以使用写入循环/f开关:

for /f "delims=" %%s in (*.txt) do (
    ...
)
Run Code Online (Sandbox Code Playgroud)

Regexps由提供findstr.stdin如果没有提供输入文件,它将匹配.您可以将输出重定向到NUL不显示找到的字符串,只需使用它errorlevel来查看它是否匹配(0表示匹配,非0表示不匹配).你可以/f再次使用分割字符串.所以:

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
    )
)
Run Code Online (Sandbox Code Playgroud)


EFr*_*aim 2

我认为在 CMD.EXE 中这样做太痛苦了,甚至完全不可能,尽管我在最后一个问题上可能是错误的。

您最好使用 WSH(Windows 脚本宿主),它允许您使用 JScript 或 VbScript,并且几乎存在于每个系统中。(如果需要,您可以提供可再发行的版本)