简体   繁体   中英

Search a text in a text file and print in CMD prompt using batch file

I want to write a batch file (.bat). Using the batch file I want to search for a unique text in a text file and print the line containing the text into console window as output. Search criteria is user input.

Which batch code is required for this task?

For example below is the content of the .txt file.

"Command Prompt, also known as cmd.exe or cmd (after its executable file name), is the command-line interpreter on Windows NT, Windows CE, OS/2 and eComStation operating systems. It is the counterpart of COMMAND.COM in DOS and Windows 9x systems (where it is also called "MS-DOS Prompt"), and analogous to the Unix shells used on Unix-like systems. The initial version of Command Prompt for Windows NT was developed by Therese Stowell.[1]"

I want to write a batch script using Windows standard commands where user inputs the search string like Windows CE and the entire line with this string gets output in command prompt window.

For example on user inputs Windows CE the output should be:

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

You don't need to create a batch file for this function. It already exists in the find tool in all versions of Windows that can be called from any cmd prompt. Here are some details on how to use it: How to Use Find from the command prompt

EDIT BASED ON COMMENTS:

The find syntax is pretty straightforward. You seem to know the file that you want to search in and you know how to prompt the user for the string:

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

The Batch file below separate the lines from input file in phrases, where a phrase is a string delimited by commas or points.

@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

Output example:

Enter the search string: Windows CE
 Windows CE

If you want better answers, please post better questions...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM