【问题标题】:DOS: find a string, if found then run another scriptDOS:查找一个字符串,如果找到则运行另一个脚本
【发布时间】:2011-01-01 21:18:18
【问题描述】:

我想使用 DOS 在文件中查找字符串:

例如

找到“字符串”status.txt

当找到它时,我想运行一个批处理文件。

最好的方法是什么?

【问题讨论】:

  • find 是否根据是否找到字符串返回不同的errorlevel 值?如果是这样,那么您的解决方案就在那里。
  • 你是说 MS-DOS 还是 Windows 上的 cmd.exe 批处理解释器?

标签: batch-file dos


【解决方案1】:
C:\test>find /c "string" file | find ": 0" 1>nul && echo "execute command here"

【讨论】:

  • 这是我最初的方法,但我不喜欢依赖 find 的输出,以后会包含 : 0。我找不到支持这一点的(双关语)文档,并认为errorlevel 方法可能更适合未来。
  • 我编辑了答案以添加 /c 开关。否则 'find' 不报告计数 (": 0")
【解决方案2】:
@echo off
cls
MD %homedrive%\TEMPBBDVD\
CLS
TIMEOUT /T 1 >NUL
CLS
systeminfo >%homedrive%\TEMPBBDVD\info.txt
cls
timeout /t 3 >nul
cls
find "x64-based PC" %homedrive%\TEMPBBDVD\info.txt >nul
if %errorlevel% equ 1 goto 32bitsok
goto 64bitsok
cls

:commandlineerror
cls
echo error, command failed or you not are using windows OS.
pause >nul
cls
exit

:64bitsok
cls
echo done, system of 64 bits
pause >nul
cls
del /q /f %homedrive%\TEMPBBDVD\info.txt >nul
cls
timeout /t 1 >nul
cls
RD %homedrive%\TEMPBBDVD\ >nul
cls
exit

:32bitsok
cls
echo done, system of 32 bits
pause >nul
cls
del /q /f %homedrive%\TEMPBBDVD\info.txt >nul
cls
timeout /t 1 >nul
cls
RD %homedrive%\TEMPBBDVD\ >nul
cls
exit

【讨论】:

    【解决方案3】:

    因为答案被标记为正确,所以它是一个 Windows Dos 提示脚本,这也可以工作:

    find "string" status.txt >nul && call "my batch file.bat"
    

    【讨论】:

    • 在 Windows 上拒绝访问
    • @Jack 你正在使用的文件或文件夹的权限有问题。
    【解决方案4】:

    我们有两个命令,第一个是“condition_command”,第二个是“result_command”。 如果我们需要在“condition_command”成功时运行“result_command”(errorlevel=0):

    condition_command && result_command
    

    如果我们需要在“condition_command”失败时运行“result_command”:

    condition_command || result_command
    

    因此,当我们在文件“status.txt”中有“字符串”时运行“some_command”:

    find "string" status.txt 1>nul && some_command
    

    如果文件“status.txt”中没有“字符串”:

    find "string" status.txt 1>nul || some_command
    

    【讨论】:

      【解决方案5】:

      我已经有一段时间没有对批处理文件做过任何事情了,但我认为以下方法可行:

      find /c "string" file
      if %errorlevel% equ 1 goto notfound
      echo found
      goto done
      :notfound
      echo notfound
      goto done
      :done
      

      这确实是一个概念证明;清理,因为它适合您的需要。关键是如果string 不在file 中,则find 会返回1errorlevel。在这种情况下我们分支到notfound,否则我们处理found 情况。

      【讨论】:

      • 最好使用if errorlevel 1。不过,它的语义略有不同,但总体上更加健壮。
      猜你喜欢
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 1970-01-01
      • 2021-09-26
      相关资源
      最近更新 更多