简体   繁体   中英

Search for a string may containing spaces and special characters in the specific type of files in entire directory structure

I have following batch script to check the specific type of files, in entire directory structure from the current directory, if a string is found in those files or not:

@echo off
set RESULT_FILE="result.txt"
set /p STR="Enter the String to Find: "
pushd %~p0
type NUL > %RESULT_FILE%.tmp
for /f "delims=" %%a in ('dir /B /S *.phtml') do (
    for /f "tokens=3 delims=:" %%c in ('find /i /c ".%STR:"=%." "%%a"') do (
        for /f "tokens=*" %%f in ('find /i ".%STR:"=%." "%%a"') do if %%c neq 0 echo %%f
    )
) >> "%RESULT_FILE%".tmp
move %RESULT_FILE%.tmp %RESULT_FILE% >nul 2>&1

:: Open the file
"%RESULT_FILE%"
popd

But my search string may contain spaces between multiple words and special characters too.

How can I modify the search string variable STR to allow spaces and special characters in the search string as literal?

Right now zero results are returned when the search string contains spaces and special characters.

The following should work. I remove the quotes before the for loop, but only the outer, how it works is explained here at ss64 . To work with special characters like a carret ( ^ ) I enabled delayed expansion.
Further it won't work with prepending and appending . in the search string, I don't know why you've added it.
I've also added a /AD so that the dir command will not list directory names.

@echo off
setlocal EnableDelayedExpansion

set RESULT_FILE="result.txt"
set /p STR="Enter the String to Find: "

:: Remove just outer quotes not quotes that are inside
set STR=###!STR!###
set STR=!STR:"###=!
set STR=!STR:###"=!
set STR=!STR:###=!

pushd %~p0
type NUL > %RESULT_FILE%.tmp
for /f "delims=" %%a in ('dir /B /S /A-D *.phtml') do (
   for /f "tokens=3 delims=:" %%c in ('find /i /c "%STR%" "%%a"') do (
      for /f "tokens=*" %%f in ('find /i "%STR%" "%%a"') do if %%c neq 0 echo %%f
   )
) >> "%RESULT_FILE%".tmp
move %RESULT_FILE%.tmp %RESULT_FILE% >nul 2>&1

:: Open the file
"%RESULT_FILE%"
popd

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