使用批处理文件搜索特定文本(字符串组)是否存在于文件中

时间:2013-04-07 12:03:25

标签: search text batch-file

我正在搜索是否使用批处理文件将特定文本(字符串组)存在于文件中。 这是我写的,但它不适用于文本。它只是为字符串工作(而不是搜索文本)。

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

例如,如果必须将文本“我吃早餐”搜索到包含“我每天都吃早餐”的文件中,命令echo必须打印出这个:     “我有早餐的文字”。

任何帮助!请。

3 个答案:

答案 0 :(得分:0)

此文件完美无缺。

找到文本所需的命令行是

yourbatch yourtextfile.txt "I have breakfast"

如果你执行

yourbatch yourtextfile.txt I have breakfast

然后它将只搜索I因为SPACE是分隔符,并且为了搜索以空格分隔的字符串,您需要"引用字符串"

同样,如果您的文件名包含空格,请使用文件名。

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

另外:小心

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,所以第二行也会被执行。

答案 1 :(得分: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

答案 2 :(得分:0)

您可以执行以下操作:

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