Search code examples
windowsbatch-filecmd

How to connect for loop with find option


How can i connect

For loop that goes on all files in folder and find in each string then add this string to a variable I need list of files in folder + find in that files line that contains "string" and give that line

Exactly what I need is this: I have a folder and in it various files x.txt y.txt and many others I need to put a list of these files into csv and find the line containing "string" and next to put the whole line example:

db.csv 
output x.txt "aaaaaa string aaaaaaa" 
y.txt "asfdsaf string dfsadsa"
FOR %%i IN (folder/*.*) DO (
        set var = find "text"
    echo %%i ; var >> db.csv
)

Solution

  • Not tested:

    @echo off
    setlocal enableDelayedExpansion
    FOR %%i IN (folder\*.*) DO (
        for /f "tokens=* delims=" %%# in ('type "%%~fi" ^| find "string"') do (
            set "var=%%#"
        )
        echo %%i ; !var! >> db.csv
    )
    

    you need a delayed expansion and nested for loop to assign a result of a command into a variable