JSI Tip 8312. How can I display the file name, line number, and line text of all files in a folder that contain a specified string?


In tip 8204, I scripted FindIt.bat to return the list of file names that contained a specified string.

If you wish to return the file name, line number, and line text that contain a specified string, use FindString.bat.

The syntax for using FindString.bat is:

\[call\] FindString StartPath Mask "String"

Where:

StartPath is the drive or folder you want to search. All sub-folders of StartPath are also searched.

Mask      is the file mask. An *.* will search all files in StartPath, 
          while a mask of *.txt will only search files with a .txt extension. 

String    is the string you are searching for.
The output is displayed on the console, but you can redirect it to a file using:

\[call\] FindString StartPath Mask "String">FileName

If you wish to process the output, use a command like:

for /f "Tokens=1-3* Delims=:""" %%a in ('FindString StartPath Mask "String"') do (
 set FileName="%%a:%%b"
 set LineNumb=%%c
 set LineText=%%d
 call :process
)
StartPath.bat contains:
@echo off
if \{%3\}==\{\} @echo Syntax: FindString Folder FileMask "String"&goto :EOF
setlocal
set folder=%1
set mask=%2
set string=%3
set folder=%folder:"=%#
set folder=%folder:/#=%
set folder=%folder:#=%
set mask=%mask:"=%
set string=%string:"=%
for /f "Tokens=*" %%f in ('dir "%folder%\%mask%" /s /b') do (
 for /f "Tokens=*"  %%t in ('type "%%f"^|findstr /L /I /N /C:"%string%"') do (
 @echo %%f:%%t
 )
)
endlocal



Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish