【问题标题】:Not getting the required output through "find" command in a for loop in Windows Batch Scripting在 Windows 批处理脚本的 for 循环中未通过“查找”命令获得所需的输出
【发布时间】:2021-07-12 14:30:51
【问题描述】:

我的要求很简单,我只想扫描当前目录中的所有文件以查找特定字符串,如果找到该字符串,我只想显示“找到字符串”,否则显示“找不到字符串”

    @ECHO OFF
    for %%f in (C:\Users\aalvoor\Desktop\BatchScript\*) do (
    echo File is %%f
    find /c "defaultModel" %%f >NUL
    if %errorlevel% equ 1 (echo File is notfound) else (echo String is found)
    )

但问题是当我没有将它放入 for 循环时它可以工作,但是当我出于某种原因将它放入 for 循环中时,我收到一条消息 String is found which is not true.

【问题讨论】:

  • 我建议打开command prompt,运行if /? 并阅读输出帮助,该帮助已在第一页解释了用于评估前运行命令或可执行文件的退出代码的推荐语法。所以使用if errorlevel 1 而不是if %errorlevel% equ 1 并且代码有效,您不必考虑延迟扩展。另见single line with multiple commands using Windows batch filethis answer about dynamic variables 的第 4 章。
  • 非常感谢大家..如果错误级别有效...而且不必使用延迟变量扩展逻辑,为此苦苦挣扎了一个多星期。实际使用了 Mofo 给出的评论.. 那么如何将其标记为接受的答案?

标签: for-loop batch-file find


【解决方案1】:

使用条件运算符&&||

&& 是如果errorlevel equ 0

|| 是如果errorlevel neq 0

@echo off
for %%f in ("%userprofile%\Desktop\BatchScript\*") do (
    echo File is %%f
    find /c "defaultModel" %%f >nul 2>&1 && echo String found || echo String NOT found
)

【讨论】:

    猜你喜欢
    • 2013-06-11
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 2013-01-25
    相关资源
    最近更新 更多