2010-01-06 48 views
17

我想用DOS來查找文件中的字符串:DOS:找到一個字符串,如果找到則運行另一個腳本

例如

找到「字符串」 status.txt中

當它被發現時,我想運行一個批處理文件。

這樣做的最好方法是什麼?

+0

不'find'返回取決於是否字符串不同'errorlevel'值被發現?如果是這樣,那麼你的解決方案就在那裏。 – 2010-01-06 00:50:43

+2

您是真的指MS-DOS還是Windows的cmd.exe批解釋器? – 2010-01-06 01:19:44

回答

5
@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 
26

它已經一段時間,因爲我已經做了批處理文件什麼,但我認爲以下工作:

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

這的確是一個概念證明;清理,因爲它適合您的需求。關鍵是如果string不在file中,find返回errorlevel1。在這種情況下,我們分支到notfound,否則我們處理found的情況。

+0

謝謝 這有助於很多 – Manjot 2010-01-06 01:44:04

+0

最好使用'if errorlevel 1'。儘管它有稍微不同的語義,但整體上更加健壯。 – Joey 2011-04-12 04:56:38

9
C:\test>find /c "string" file | find ": 0" 1>nul && echo "execute command here" 
+2

這是我最初的方法,但我不喜歡依賴於'find'的輸出,因爲它包含':0'。我找不到(雙關語)文檔支持這一點,並認爲'errorlevel'方法可能會更有前途。 – jason 2010-01-06 01:36:07

+0

我編輯了答案以添加/ c開關。否則,「查找」不會報告計數(「:0」) – Spikolynn 2017-11-16 11:44:53

6

我們有兩個命令,第一個是「condition_command」,第二個是「result_command」。 如果我們需要運行 「result_command」 當 「condition_command」 是成功的(錯誤級別= 0):

condition_command && result_command 

如果我們需要運行 「result_command」 當 「condition_command」 是失敗的:

condition_command || result_command 

因此,對於萬一

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

,當我們在文件「status.txt中」沒有「串」:萬一運行「some_command」當我們在文件「status.txt中」有「字符串」

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

的答案被標記爲正確的,那麼這是一個Windows DOS提示符腳本,這將工作太:

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

訪問在Windows上被拒絕 – Clayton 2014-08-12 10:20:08

+0

@Jack這是對您正在使用的文件或文件夾的權限問題。 – foxidrive 2014-08-12 10:42:12

相關問題