Tulga
Tulga

Reputation: 3

Batch file to perform a looped search based on the line items of a text file

I have been reading great posts in this forum and got close to what I want to do but couldn't figure out the exact code.

I want to create a windows batch file to do following:

Thanks.

Upvotes: 0

Views: 2490

Answers (3)

jeb
jeb

Reputation: 82418

There are multiple problems.

FIND /i "%A%" ... can't work, the name of the FOR-Varibale is %%A
And the second proble: With FIND you check the content of the file not the name. And you should use indention to avoid too much parenthesis.

You better try

FOR /F "tokens=*" %%A IN (%listfile%) DO (
    FOR %%f in (%searchdir%\*) do ( 
        set "filename=%%~f"
        set replaced=!filename:%%A=!
        if !replaced! NEQ !filename! (
           echo !filename! contains '%%A'
        )
    )
)

It tries to replace %%A inside of the filename with . If the replaced is not equal the filename, the filename must contain %%A

Upvotes: 0

Tulga
Tulga

Reputation: 3

I wrote the following code but not sure if I am in the right track. Here is my setup: list.txt file contents are (my keywords for the filename search) --

one
two
five
ten
six

f1 folder contains --

four.txt
one.txt
three.txt

I want to move the matching ones to F2 folder, but the code simplicity I am using echo instead.

My code is:

@ECHO OFF
SETLOCAL EnableDelayedExpansion


SET listfile=D:\batchtest\list.txt
SET searchdir=D:\batchtest\f1

FOR /F "tokens=*" %%A IN (%listfile%) DO (

FOR %%f in (%searchdir%\*) do (FIND /i "%A%" %%f
    if errorlevel 1 (
echo Search failed) else (
echo Search successful
)   
)
)
)

It is running but not finding matching filenames.

Thanks.

Upvotes: 0

atzz
atzz

Reputation: 18010

I'm not running Windows at the moment, so I can only post some ideas, not the solution.

1) Use for /f to iterate over file contents.

2) Use find "%Keyword%" %SourceDir% to get the list of matching files. You will have to parse out file names from the output of find.

2a) As an alternative, you can iterate over files in the source dir (with nested for) and call find for each file, discarding its output and using its exit code (%ERRORLEVEL%) to decide whether the file matches (it will return 0 if there is a match and nonzero if there is no match). Something like this:

for %%F in (%SourceDir%\*) do (
    find "%Keyword%" %%F > nul
    if not errorlevel 1 (echo File %%F matches) else (echo File %%F does not match)
)

3) Move matching files with move.

Upvotes: 1

Related Questions