如何使用 Windows 命令行查找文件是否包含给定字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5626879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 08:16:05  来源:igfitidea点击:

How to find if a file contains a given string using Windows command line

windowsbatch-filecmd

提问by Jai

I am trying to create a batch (.bat) file for windows XP to do the following:

我正在尝试为 Windows XP 创建一个批处理 (.bat) 文件以执行以下操作:

If (file.txt contains the string 'searchString') then (ECHO found it!) 
ELSE(ECHO not found)

So far, I have found a way to search for strings inside a file using the FINDcommand which returns the line in the file where it finds the string, but am unable to do a conditional check on it.

到目前为止,我已经找到了一种使用FIND命令在文件中搜索字符串的方法,该命令返回文件中找到字符串的行,但无法对其进行条件检查。

For example, this doesn't work.

例如,这不起作用。

IF FIND "searchString" file.txt ECHO found it!

Nor does this:

这也没有:

IF FIND "searchString" file.txt=='' ECHO not found

Any Ideas on how this can be done?

关于如何做到这一点的任何想法?

回答by Mike Q

From other post:

来自其他帖子:

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

Or something like: if not found write to file.

或类似:如果未找到写入文件。

    find /c "%%P" file.txt  || ( echo %%P >> newfile.txt )

Or something like: if found write to file.

或类似:如果找到写入文件。

    find /c "%%P" file.txt  && ( echo %%P >> newfile.txt )

Or something like:

或类似的东西:

    find /c "%%P" file.txt  && ( echo found ) || ( echo not found )

回答by Pedro Francisco Pereira

I've used a DOScommand line to do this. Two lines, actually. The first one to make the "current directory" the folder where the file is - or the root folder of a group of folders where the file can be. The second line does the search.

我使用DOS命令行来执行此操作。实际上是两行。第一个使“当前目录”成为文件所在的文件夹 - 或文件所在的一组文件夹的根文件夹。第二行进行搜索。

CD C:\TheFolder
C:\TheFolder>FINDSTR /L /S /I /N /C:"TheString" *.PRG

You can find details about the parameters at this link.

您可以在此链接中找到有关参数的详细信息。

Hope it helps!

希望能帮助到你!