Batch file DOS:查找字符串,如果找到,则运行另一个脚本
我想使用DOS在文件中查找字符串: 比如说 查找“字符串”status.txt 找到后,我想运行一个批处理文件Batch file DOS:查找字符串,如果找到,则运行另一个脚本,batch-file,dos,Batch File,Dos,我想使用DOS在文件中查找字符串: 比如说 查找“字符串”status.txt 找到后,我想运行一个批处理文件 做这件事的最佳方法是什么?我已经有一段时间没有用批处理文件做过任何事情了,但我认为以下方法可行: find /c "string" file if %errorlevel% equ 1 goto notfound echo found goto done :notfound echo notfound goto done :done 这确实是一个概念证明;根据你的需要进行清理。关键是
做这件事的最佳方法是什么?我已经有一段时间没有用批处理文件做过任何事情了,但我认为以下方法可行:
find /c "string" file
if %errorlevel% equ 1 goto notfound
echo found
goto done
:notfound
echo notfound
goto done
:done
这确实是一个概念证明;根据你的需要进行清理。关键是
find
如果字符串不在文件中,则返回1
的errorlevel
。在这种情况下,我们分支到notfound
,否则我们处理found
情况。我们有两个命令,第一个是“条件命令”,第二个是“结果命令”。
C:\test>find /c "string" file | find ": 0" 1>nul && echo "execute command here"
如果我们需要在“条件命令”成功时运行“结果命令”(errorlevel=0):
如果我们需要在“条件命令”失败时运行“结果命令”:
因此,如果文件“status.txt”中有“string”,请运行“some_命令”:
如果文件“status.txt”中没有“string”:
如果答案被标记为正确,则它是一个Windows Dos提示脚本,这也会起作用:
find "string" status.txt >nul && call "my batch file.bat"
根据是否找到字符串,find
是否返回不同的errorlevel
值?如果是这样,你的解决方案就在那里。你真的是指MS-DOS还是指Windows上的cmd.exe批处理解释器?这是我最初的方法,但我不喜欢依赖find
的输出,从此包含:0
。我找不到支持这一点的(双关语)文档,并且认为errorlevel
方法可能更适合未来。我编辑了答案,添加了/c开关。否则,“查找”不会报告计数(:0)。如果错误级别为1,则最好使用。不过,它的语义稍有不同,但总体上更为健壮。上拒绝访问windows@Jack这是您对正在使用的文件或文件夹的权限有问题。
condition_command || result_command
find "string" status.txt 1>nul && some_command
find "string" status.txt 1>nul || some_command
find "string" status.txt >nul && call "my batch file.bat"
@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