Jolin
Jolin

Reputation: 241

Loop a list of text files in same directory and findstr "keyword" in the txt file (batch script)

I would like to create a script where loop through all the .txt files in the same directory and search for keyword.

If keyword is found, echo the filename.txt and keyword found to a temp.txt
Else echo the filename.txt and keyword not found to a temp.txt

Current code:

for /r D:\Users\hi\Documents\bat_for_random %%X in (*.txt) 
findstr "HELLO KEYWORD " %%X &&
(
echo "keyword found" %%X  >temp.txt
)
|| (
echo "keyword not found" %%X  >temp.txt
)
pause

Upvotes: 0

Views: 527

Answers (2)

Compo
Compo

Reputation: 38719

There is no need to have two lists, one containing matches and one not. In the real world you need one or the other.

To get a list of the files with string matches is a single command line, (no need for For loops etc.):

FindStr/SMC:"HELLO KEYWORD " "D:\Users\hi\Documents\bat_for_random\*.txt">"temp.txt"

Upvotes: 0

aschipfl
aschipfl

Reputation: 34989

Your for syntax is wrong, the do keyword is missing. In addition, you placed &&/|| and the parentheses wrongly, you need to put them in one line. Finally, your redirection operator > overwrites the text file temp.txt every time the loop iterates; using >> instead would append to the text file; or, even better, you can redirect all the lines once only. So here is the improved code:

> "temp.txt" (
    for /R "D:\Users\hi\Documents\bat_for_random" %%X in ("*.txt") do (
        > nul findstr /C:"HELLO KEYWORD " "%%~X" && (
            echo keyword found "%%~nxX"
        ) || (
            echo keyword not found "%%~nxX"
        )
    )
)

Upvotes: 2

Related Questions