DOS:找到一个字符串,如果找到则运行另一个脚本

Man*_*jot 19 dos batch-file

我想使用DOS在文件中找到一个字符串:

例如

找到"string"status.txt

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

做这个的最好方式是什么?

jas*_*son 28

这已经有一段时间了,因为我已经对批处理文件做了任何事情,但我认为以下工作:

find /c "string" file
if %errorlevel% equ 1 goto notfound
echo found
goto done
:notfound
echo notfound
goto done
:done
Run Code Online (Sandbox Code Playgroud)

这确实是一个概念证明; 清理,因为它符合您的需求.关键是,find返回errorlevel1,如果string不在file.notfound在这种情况下我们分支,否则我们处理found案件.


gho*_*g74 10

C:\test>find /c "string" file | find ": 0" 1>nul && echo "execute command here"
Run Code Online (Sandbox Code Playgroud)

  • 这是我最初的方法,但我不喜欢依赖于`find`的输出,因此包含`:0`.我找不到(双关语)文档支持这一点,并认为`errorlevel`方法可能更具未来性. (2认同)

小智 7

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

condition_command && result_command
Run Code Online (Sandbox Code Playgroud)

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

condition_command || result_command
Run Code Online (Sandbox Code Playgroud)

因此,如果在"status.txt"文件中有"string",则运行"some_command":

find "string" status.txt 1>nul && some_command
Run Code Online (Sandbox Code Playgroud)

如果我们在"status.txt"文件中没有"string":

find "string" status.txt 1>nul || some_command
Run Code Online (Sandbox Code Playgroud)


fox*_*ive 6

由于答案标记正确,因此它是一个Windows Dos提示脚本,这也将起作用:

find "string" status.txt >nul && call "my batch file.bat"
Run Code Online (Sandbox Code Playgroud)


小智 6

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