首页 文章

搜索文本文件中的文本,并使用批处理文件在CMD提示符下打印

提问于
浏览
0

我想写一个批处理文件(.bat) . 使用批处理文件我想在文本文件中搜索唯一文本,并将包含文本的行打印到控制台窗口作为输出 . 搜索条件是用户输入 .

此任务需要哪个批次代码?

例如,下面是.txt文件的内容 .

“命令提示符,也称为cmd.exe或cmd(在其可执行文件名之后),是Windows NT,Windows CE,OS / 2和eComStation操作系统上的命令行解释器 . 它是COMMAND.COM的对应物在DOS和Windows 9x系统中(也称为“MS-DOS提示符”),类似于类Unix系统上使用的Unix shell.Windows NT命令提示符的初始版本由Therese Stowell开发 . [1 ]”

我想使用Windows标准命令编写批处理脚本,其中用户输入搜索字符串,如 Windows CE ,带有此字符串的整行在命令提示符窗口中输出 .

例如,在用户输入 Windows CE 上,输出应为:

is the command-line interpreter on Windows NT, Windows CE, OS/2 and eComStation

2 回答

  • 1

    您无需为此功能创建批处理文件 . 它已存在于所有Windows版本的 find 工具中,可以从任何 cmd 提示符调用 . 以下是有关如何使用它的一些细节:How to Use Find from the command prompt

    基于评论的编辑:

    find 语法非常简单 . 您似乎知道要搜索的文件,并且您知道如何提示用户输入字符串:

    set /P search_string= Enter the string you would like to search for:
    find "%search_string%" C:\ServiceLog%_store%.txt
    
  • 1

    下面的批处理文件将短语中的行与输入文件分开,其中短语是由逗号或点分隔的字符串 .

    @echo off
    setlocal EnableDelayedExpansion
    
    set /P "userString=Enter the search string: "
    
    rem Process all lines in file
    for /F "delims=" %%a in (input.txt) do (
       set "line=%%a"
    
       rem Split all phrases in line
       call :splitPhrases
    
       rem Process each phrase
       for /L %%i in (1,1,!numPhrases!) do (
    
          rem If the user string appears in this phrase
          if "!phrase[%%i]:%userString%=!" neq "!phrase[%%i]!" (
             rem ... show it
             echo !phrase[%%i]!
          )
    
       )
    )
    goto :EOF
    
    
    :splitPhrases
    set "numPhrases=0"
    
    :nextPhrase
       for /F "tokens=1* delims=.," %%a in ("!line!") do (
          set /A numPhrases+=1
          set "phrase[!numPhrases!]=%%a"
          set "line=%%b"
       )
    if defined line goto nextPhrase
    exit /B
    

    输出示例:

    Enter the search string: Windows CE
     Windows CE
    

    如果您想要更好的答案,请发布更好的问题......

相关问题