Batch Script to find string in directory and all subdirectories

directory, root, string

Solution

You have a few mistakes in your script:

There should not be a space after the equals sign of a `set` command. Specifically, remove the space after `set /p "var1=`.

To expand variables, you have to put a percent sign before and after the variable name, so instead of `%var` use `%var%`.

Not directly related to your problem, but why are you invoking `find` twice?

I've also made use of a temporary file, so that `result.txt` won't be searched by `find`.

Note that for if you're running the batch script from a file, You need to use double percent signs when you use loop variables, for example: `%%a`

Anyway, here's the fixed script, hopefully doing what you intended to do:

@echo off
set RESULT_FILE="result.txt"
set /p "var1=Enter the String to Find: "

pushd %~p0
type NUL > %RESULT_FILE%.tmp
for /f "delims=" %%a in ('dir /B /S *.txt') do (
    for /f "tokens=3 delims=:" %%c in ('find /i /c "%var1%" "%%a"') do (
        for /f "tokens=*" %%f in ('find /i "%var1%" "%%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

Problem

I want to write a batch file which used the find command to find a string in the parent directory and all sub directories, and prints that output to a text file, then opens the text file when done. My code so far looks like this: ``` @echo off set /p "var1= Enter the String to Find: " for /F "delims=" %a in ('dir /B /S *.txt') do @(find /i "%var1" "%a" 1>nul 2>&1 && find /i "%var1" "%a") >> result.txt start result.txt ``` But this is currently not even writing anything to result.txt, even though I am sure that where I am searching the string appears in multiple .txt files. I know it must be something syntax-wise but I can't seem to figure it out.

Original source