检查"IF"是否正确FOR循环内的条件(批处理/cmd) [英] check "IF" condition inside FOR loop (batch/cmd)
问题描述
我需要在Windows批处理文件中实现的代码是这样的(它当前在Perl中):
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++;
}
}
我的问题是:
- Windows批处理文件中是否可能具有这种复杂性?
- 如果是,我该如何设置If条件 在for循环中读取文本 文件?
- Is this level of complexity possible in Windows batch files?
- 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.
我正在Windows中工作.默认情况下,我只能使用Windows提供的任何功能,这意味着我不能使用Unix实用程序.
I am working in Windows. I can use only whatever is provided with Windows by default and that means I cant use Unix utilities.
推荐答案
将if
放入for
通常很容易:
for ... do (
if ... (
...
) else if ... (
...
) else (
...
)
)
可以使用/f
开关编写遍历行的for
循环:
A for
loop that iterates over lines can be written using /f
switch:
for /f "delims=" %%s in (*.txt) do (
...
)
正则表达式由findstr
提供.如果未提供输入文件,它将与stdin
匹配.您可以将输出重定向到NUL
,以使其不显示找到的字符串,而只需使用其errorlevel
来查看其是否匹配(0表示匹配,非0表示不匹配).您可以再次使用/f
分割字符串.所以:
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
)
)
这篇关于检查"IF"是否正确FOR循环内的条件(批处理/cmd)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!