2013-04-07 76 views
0

我正在使用批處理文件搜索特定文本(字符串組)是否存在於文件中。 這是我寫的,但它不適用於文本。它只適用於字符串(不搜索文本)。使用批處理文件搜索特定文本(字符串組)是否存在於文件中

rem %1 is name of the file whose text is being found 
FindStr /C:%2 %1 
If %ERRORLEVEL% EQU 0 echo text %2 is Present 
If %ERRORLEVEL% EQU 1 echo text %2 is not Present 

例如,如果「吃早餐」的文本必須被搜索到包含文件「我每天吃早餐」,命令回聲必須打印這一個: 「文吃早餐存在」。

任何幫助!請。

回答

0

此文件完美地工作。

你需要找到你的文字的命令行是

yourbatch yourtextfile.txt "I have breakfast" 

如果執行

yourbatch yourtextfile.txt I have breakfast 

則因爲空間是一個分隔符,將只搜索I,爲了尋找一個空格分隔的字符串,您需要"報價字符串"

同樣,就此而言,w如果文件名包含空格,則使用文件名。

yourbatch "your text file.txt" "I have breakfast" 


%%1 is "your text file.txt" 
%%2 is "I have breakfast" 

包括引號。

要刪除引號,如果你想,你會使用%〜2

所以 - 你可以ECHO

ECHO with quotes:%2 and without: %~2 

ALSO:小心

If %ERRORLEVEL% EQU 0 echo text %2 is Present 
If %ERRORLEVEL% EQU 1 echo text %2 is not Present 

ECHO是少數不改變errorlevel的命令之一。很多人改變它,所以例如,如果你寫

如果%ERRORLEVEL%EQU 0回聲Y |找到 「X」> NUL 如果%ERRORLEVEL%EQU 1個回聲文本%2不存在

那麼如果發現echo Y|find "x" >nul是因爲上一步中的errorlevel爲0,那麼因爲echo Y|find "x" >nul將errorlevel設置爲1,第二行也將被執行。

+0

這是偉大的!也感謝細節。 – tamo 2013-04-07 12:55:23

0

這應該工作,如果你調用腳本script.bat "file name" "search string"

@echo off&setlocal 
rem %1 is name of the file whose text is being found 
FindStr /C:"%~2" "%~1" >nul 
If %ERRORLEVEL% EQU 0 echo text %2 is Present 
If %ERRORLEVEL% EQU 1 echo text %2 is not Present 
0

你可以做到以下幾點:

FindStr /C:"%~2" "%~1" >nul && echo text "I have breakfast is present". 
相關問題