Reputation: 131
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.
Upvotes: 0
Views: 547
Reputation: 5631
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 /A-D
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
Upvotes: 1